我正在使用 Ruby on Rails 3,并且我正在尝试扩展一个类 Account 以“以 Rails 方式”处理错误。
在我的模型中,我有
class Users::Account
extend ActiveModel::Naming
extend ActiveModel::Translation
include ActiveModel::Validations
include ActiveModel::Conversion
def persisted?
false
end
attr_reader :errors
def initialize(attributes = {})
@errors = ActiveModel::Errors.new(self)
@firstname = attributes[:firstname]
@lastname = attributes[:lastname]
...
end
end
我想在上面的类中“封装”以下哈希使用ActiveModel::Errors
---
errors:
base: Invalid account.
firstname: Too short.
这样我就可以在类中插入上述错误哈希后,像这样
@account.errors # => Hash of errors
测试场景的调试(总是)如下,因为我不知道如何将错误附加到类。
firstname: T
lastname: Test surname
errors: !omap []
我怎样才能做到这一点?