在错误文本中禁止"base"以自定义Rails嵌套属性的验证

Kev*_*vin 5 custom-validators nested-attributes ruby-on-rails-3

我有以下型号:

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
Run Code Online (Sandbox Code Playgroud)

我有一个评估表单,其中包含EvaluationInstitution和EvaluationInstitutionDepartment的嵌套属性,因此我的表单嵌套到3个级别.第3级给我一个问题.

错误按预期触发,但是当require_at_least_one_department的错误触发时,文本将读取

评估机构基地请至少选择一个部门

该消息应显示为"请选择至少一个部门".

如何删除"评估机构基础"?

小智 6

在Rails 3.2中,如果您查看方法full_message的实现,您将看到它通过I18n显示错误消息,格式为"%{attribute}%{message}".

这意味着您可以在I18n语言环境中自定义显示的格式,如下所示:

activerecord:
  attributes:
    evaluation_institutions:
      base: ''
Run Code Online (Sandbox Code Playgroud)

这将取消你想要的前缀"评估机构基础".