Vig*_*esh 5 validation activerecord ruby-on-rails-3
在验证ActiveRecord模型中字段的数字时,如何自定义子选项的错误消息?
例:
validates :month, :numericality => {
:greater_than_or_equal_to => 1,
:less_than_or_equal_to => 12
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果'month'属性超过12,我想提供自定义错误消息,而不是默认的"必须小于或等于12".怎么做到这一点?
如果您不想使用自定义验证器,则可以使用该en.yml文件.假设"post"是您的模型名称,它提供了特定于年龄的消息,特定于帖子的消息和通用(所有模型)消息的示例.
en:
activerecord:
errors:
models:
post:
attributes:
age:
less_than_or_equal_to: "Age-specific error" # Applies only to post.age
less_than_or_equal_to: "Post-specific error" # Applies to all other fields for a post
messages:
less_than_or_equal_to: "Generic error" # Applies to all other models
Run Code Online (Sandbox Code Playgroud)