我看到模型中使用了自定义验证器(很好),但我也看到验证器本身添加到记录错误对象中。
例如我懂了
(更改示例)
class Title < ActiveRecord::Base
# implement the method called during validation
def validate_each(record, attribute, value)
record.errors[attribute] << 'must be Mr / Mrs / Dr.' unless ['Mr.', 'Mrs.', 'Dr.'].include?(value)
end
end
这感觉有点像应该在 Controller 中完成的状态事情,验证应该只返回 true
/false
但也许不会。
最佳答案
我倾向于这种模式:
errors.add[:name] << :invalid_honorific
其中模型设置的错误是一个符号(更像是一个错误代码),然后由 View 层处理,.yml
文件等等。这避免了在模型中放置过多的表示层内容。
关于ruby-on-rails - rails 自定义验证器 - 添加到模型或 Controller 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8169797/