ruby-on-rails-3nested-attributescustom-validators

Suppress "base" in error text for custom validation of Rails nested attributes


I have the following models:

class Evaluation < ActiveRecord::Base
    attr_accessible :product_id, :description, :evaluation_institutions_attributes

    has_many :evaluation_institutions, :dependent => :destroy  
    accepts_nested_attributes_for :evaluation_institutions, :reject_if => lambda { |a| a[:token].blank? }, :allow_destroy => true       

    validate :requires_at_least_one_institution

    private

      def requires_at_least_one_institution
        if evaluation_institution_ids.nil? || evaluation_institution_ids.length == 0
          errors.add_to_base("Please select at least one institution")
        end
      end    
end

class EvaluationInstitution < ActiveRecord::Base

  attr_accessible :evaluation_institution_departments_attributes, :institution_id

  belongs_to :evaluation

  has_many :evaluation_institution_departments, :dependent => :destroy  
  accepts_nested_attributes_for :evaluation_institution_departments, :reject_if => lambda { |a| a[:department_id].blank? }, :allow_destroy => true

  validate :requires_at_least_one_department

  private

    def requires_at_least_one_department
       if evaluation_institution_departments.nil? || evaluation_institution_departments.length == 0
         errors.add_to_base("Please select at least one department")
       end
    end

end

class EvaluationInstitutionDepartment < ActiveRecord::Base
  belongs_to :evaluation_institution
  belongs_to :department
end

I have a form for Evaluation that includes nested attributes for EvaluationInstitution and EvaluationInstitutionDepartment, so my form is nested to 3 levels. The 3rd level is giving me a problem.

The errors are triggered as expected, but when the error triggers for requires_at_least_one_department, the text reads

Evaluation institutions base Please select at least one department

The message should read "Please select at least one department".

How do I remove "Evaluation institutions base"?


Solution

  • In Rails 3.2, if you take a look at the implementation of method full_message, you will see that it displays error messages through I18n with format "%{attribute} %{message}".

    It means that you can customize the displayed format in your I18n locales as follows:

    activerecord:
      attributes:
        evaluation_institutions:
          base: ''
    

    That would get rid of the prefix "Evaluation institutions base" as you wanted.