使用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
进行验证(并非特定于单个属性)?
答案 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)
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)
看起来这样做是不可能的。我必须在验证方法中手动添加错误消息。