将 ActiveModel 错误添加到 ruby class
Adding ActiveModel Errors to ruby class
我正在尝试让活动模型错误在我用于条带的标准 ruby class 中工作。
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>
这显然是因为它是一个数组,格式不正确。
您的代码应该可以填充 errors
。问题是您不能在 checking_account
上调用 .errors
,因为 checking_account
中的 return 值是一个数组,而不是一个 Payment 实例。您应该能够在控制台上单独进行这些调用以查看:
payment = Payment.new(user: User.find(1)) # Returns Payment instance
payment.checking_account
payment.errors # Calls `errors` on Payment instance
我正在尝试让活动模型错误在我用于条带的标准 ruby class 中工作。
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>
这显然是因为它是一个数组,格式不正确。
您的代码应该可以填充 errors
。问题是您不能在 checking_account
上调用 .errors
,因为 checking_account
中的 return 值是一个数组,而不是一个 Payment 实例。您应该能够在控制台上单独进行这些调用以查看:
payment = Payment.new(user: User.find(1)) # Returns Payment instance
payment.checking_account
payment.errors # Calls `errors` on Payment instance