如何自动为“验证”设置错误消息?

时间:2018-02-01 10:57:47

标签: ruby-on-rails error-handling rails-i18n

使用validates对特定属性进行验证后,可以使用:message选项指定验证失败时要使用的i18n消息的密钥:

模特:

class Foo < ApplicationRecord
  validates :some_attribute, ...., message: :bar
end

在语言环境中:

en:
  activerecord:
    errors:
      models:
        foo:
          attributes:
            some_attribute:
              bar: "Blah blah"

如何使用validate方法代替validates进行验证(并非特定于单个属性)?

2 个答案:

答案 0 :(得分:2)

validate与块一起使用

class Foo < ApplicationRecord
  validate do
    if ERROR_CONDITION
      errors.add(:some_attribute, :bar)
    end
  end
end

使用validate和方法

class Foo < ApplicationRecord
  validate :some_custom_validation_name

  private

  def some_custom_validation_name
    if ERROR_CONDITION
      errors.add(:some_attribute, :bar)
    end
  end
end

errors.add可以像以下一样使用:

  • errors.add(ATTRIBUTE_NAME,SYMBOL)

    • SYMBOL对应于message名称。请参阅message column here in this table
    • 即。这可以是:blank:taken:invalid:bar(您的自定义message名称)

      errors.add(:some_attribute, :taken)
      # => ["has already been taken"]
      
      errors.add(:some_attribute, :invalid)
      # => ["has already been taken", "is invalid"]
      
      errors.add(:some_attribute, :bar)
      # => ["has already been taken", "is invalid", "Blah blah"]
      
  • errors.add(ATTRIBUTE_NAME,SYMBOL,HASH)

    • 与上述相同,但您也可以将参数传递给消息。请参阅您需要使用的interpolation column here in the same table

      errors.add(:some_attribute, :too_short, count: 3)
      # => ["is too short (minimum is 3 characters)"]
      errors.add(:some_attribute, :confirmation, attribute: self.class.human_attribute_name(:first_name))
      # => ["is too short (minimum is 3 characters)", "doesn't match First name"]
      
  • errors.add(ATTRIBUTE_NAME,STRING)

    • 或传递自定义消息字符串

      errors.add(:some_attribute, 'is a bad value')
      # => ["is a bad value"]
      

另外,假设您打算将:bar作为参数传递给您的验证,就像在您的示例中一样,那么您可以使用自定义验证器:

# app/validators/lorem_ipsum_validator.rb
class LoremIpsumValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if ERROR_CONDITION
      record.errors.add(attribute, options[:message])
    end
  end
end

# app/models/foo.rb
class Foo < ApplicationRecord
  validates :some_attribute, lorem_impsum: { message: :bar }
  # or multiple attributes:
  validates [:first_name, :last_name], lorem_impsum: { message: :bar }

  # you can also combine the custom validator with any other regular Rails validator like the following
  # validates :some_attribute,
  #   lorem_impsum: { message: :bar },
  #   presence: true,
  #   length: { minimum: 6 }
end

答案 1 :(得分:-1)

看起来这样做是不可能的。我必须在验证方法中手动添加错误消息。