如何使用“ActiveModel::Errors”将错误附加到类中模块

发布于 2024-10-20 22:16:03 字数 989 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只涨不跌 2024-10-27 22:16:03

您实际上可以获取

somemodel_instance.errors.add(:some_attr, "some error message")

更多信息,请参阅此处,希望这有帮助 =)

you can actually just do

somemodel_instance.errors.add(:some_attr, "some error message")

for more info, refer to here, hope this helps =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文