我使用这个验证:
validates_numericality_of :price, :greater_than_or_equal_to => 0, :less_than => 1000000
如何为以下每种情况设置不同的:message
?
价格
< 0价格
>= 1000000
最佳答案
假设您使用的是 Rails 3,您还有另一个选择是创建自定义验证器:
# You can put this in lib/better_numericality_validator.rb
class BetterNumericalityValidator < ActiveModel::EachValidator
def validate_each(record,attribute,value)
if value < 0
record.errors[attribute] << "must be greater than or equal to 0"
elsif value >= 1000000
record.errors[attribute] << "must be less than 1000000")
end
end
end
然后您可以在您的模型中使用自定义验证器:
# In your model.rb
validates :price, :better_numericality => true
这个方法和Anubhaw的回答很相似。但是将逻辑拉出到自定义验证器中可以使您可以轻松地在其他地方重用验证,您可以轻松地单独对验证器进行单元测试,我个人认为 validates :price, :better_numericality => true
使您的模型看起来比其他模型更干净。
关于ruby-on-rails - rails : How to set different ":message" for each one of the possible errors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4468013/