如何更改关联的验证错误消息?

时间:2013-11-19 12:43:05

标签: ruby-on-rails activerecord ruby-on-rails-4

我有一个Document班,has_many :fields。每个Field对象都有name属性。

当我验证文档和相关字段时,我会收到以下每个无效字段关联的验证错误消息:

Fields is invalid.

这是一个非常无用的错误消息。相反,我希望它说:

Field '<value of the name attribute>' is invalid.

例如:

Field 'subject' is invalid.
Field 'date' is invalid.

我该怎么做?

5 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

不幸的是,似乎没有一种简单的方法可以自定义自动验证的关联,这绝对是Rails可以增强的。但是,您可以关闭has_many上关联的自动验证(但请确保以某种方式手动验证它们):

has_many :fields, validate: false

然后,例如,您可以手动添加通用消息,例如:

validates_associated :fields, message: "ARE Invalid."

但请注意,这将取代所有字段验证的消息,而不仅仅是&#34;无效&#34;

如果您需要包含无效名称值的更多自定义消息,则必须在before_save挂钩中进行手动验证

答案 2 :(得分:0)

I have the same issue. no good answer so far. So I solved it by myself. by replacing association error message with detail error message:

create a concern file models/concerns/association_error_detail_concern.rb:

module AssociationErrorDetailConcern
  extend ActiveSupport::Concern

  included do
    after_validation :replace_association_error_message
  end

  class_methods do
    def association_names
      @association_names ||= self.reflect_on_all_associations.map(&:name)
    end
  end


  def replace_association_error_message
    self.class.association_names.each do |attr|
      next unless errors[attr]
      errors.delete(attr)
      Array.wrap(public_send(attr)).each do |record|
        record.errors.full_messages.each do |message|
          errors.add(attr, message)
        end
      end
    end
  end
end

then include it in your model:

class Shop::Product < ApplicationRecord
  include AssociationErrorDetailConcern
  ...
end

答案 3 :(得分:0)

config / locales / en.yml

en:
  activerecord:
    attributes:
      cricket: #model name 
        game: "" # attribute name ( can be game_id)
    errors:
      models:
        cricket: # model name
          attributes:
            game: # attribute name
              required: "Error message has been changed."

答案 4 :(得分:0)

在en.yml中放入值并在错误消息中使用它对我有用,但我也必须提供静态消息,该消息也需要在每个字段名称后附加。我找到了一种简单的方法来执行此操作,执行完此操作后,我不必在en.yml中放入任何内容。改用

validate:field,validates_associated:{消息:“%{model}无效”}}

您可以尝试以下关键字:

  • 模型
  • 属性