如何使用“ActiveModel::Errors”将错误附加到类中模块
我正在使用 Ruby on Rails 3,并且尝试按顺序扩展类帐户 以“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 []
我该怎么做?
I am using Ruby on Rails 3 and I am trying to exend a class Account in order to handle errors "a la Rails way".
In my model I have
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
I would like to "encapsulate" in the above class the following hash using the ActiveModel::Errors
---
errors:
base: Invalid account.
firstname: Too short.
so that I can do, after inserting the above error hash in the class, like this
@account.errors # => Hash of errors
A debug for a testing scenario is (always) the following because I don't know how to append errors to the class.
firstname: T
lastname: Test surname
errors: !omap []
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上可以获取
更多信息,请参阅此处,希望这有帮助 =)
you can actually just do
for more info, refer to here, hope this helps =)