将ActiveModel错误添加到ruby类

时间:2016-03-17 11:33:15

标签: ruby-on-rails activemodel

我正在尝试让Active Model Errors在我用于条带的标准ruby类中工作。

class Payment
  attr_reader :user, :token, :errors
  attr_accessor :base
  extend ActiveModel::Naming

  def initialize(args)
    @user    = args[:user]
    @token   = args[:stripe_token]
    @errors  = ActiveModel::Errors.new(self)
  end

  def checking_account
    begin
      account = Stripe::Account.retrieve(user.stripe_account_id)
      account.external_account = token
      account.save
    rescue Stripe::StripeError => e
      errors.add(:base, e.message)
    end
  end

  # The following methods are needed to be minimally implemented

  def read_attribute_for_validation(attr)
    send(attr)
  end

  def Payment.human_attribute_name(attr, options = {})
    attr
  end

  def Payment.lookup_ancestors
    [self]
  end
end

现在我正在通过不提供令牌而故意使checking_account失败,而我刚刚返回了一个目前正在说的数组:

 => ["Invalid external_account object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'"]

现在我已经按照http://api.rubyonrails.org/classes/ActiveModel/Errors.html上的步骤进行了操作,所以我不确定为什么这不起作用,有人知道如何解决这个问题吗?

当我打电话时:

Payment.new(user: User.find(1)).managed_account它会触发上面的数组,如果我尝试调用.errors就可以了

NoMethodError: undefined method `errors' for #<Array:0x007f80989d8328>

这显然是因为它是一个数组并且格式不正确。

1 个答案:

答案 0 :(得分:0)

您拥有的代码应该用于填充errors。问题是您无法在.errors上调用checking_account,因为checking_account的返回值是数组,而不是付款实例。您应该能够在控制台上单独进行这些调用以查看:

payment = Payment.new(user: User.find(1))  # Returns Payment instance
payment.checking_account
payment.errors  # Calls `errors` on Payment instance