【问题标题】:How to append errors to a class using the 'ActiveModel::Errors' module如何使用“ActiveModel::Errors”模块将错误附加到类
【发布时间】:2011-08-27 04:47:13
【问题描述】:

我正在使用 Ruby on Rails 3,我正在尝试按顺序扩展一个类帐户 to handle errors "a la Rails way"

在我的模型中

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 []

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 hash activemodel


    【解决方案1】:

    其实你可以这样做

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

    更多信息,请参考here,希望对您有所帮助=)

    【讨论】:

    • 如果是这样的话,hash 可能不是一个好方法,不是吗?或者如果你坚持使用哈希,你可能不得不按照 {:attr_1 => "message 1", :attr_2 => "message 2"}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    相关资源
    最近更新 更多