Ruby on rails 处理模型中的条带错误
在模型中使用方法时,是否可以将条带错误消息呈现为通知。这是我现在的控制器Ruby on rails 处理模型中的条带错误,ruby-on-rails,ruby,ruby-on-rails-4,stripe-payments,Ruby On Rails,Ruby,Ruby On Rails 4,Stripe Payments,在模型中使用方法时,是否可以将条带错误消息呈现为通知。这是我现在的控制器 def create @donation = @campaign.donations.create(donation_params) if @donation.save_with_payment redirect_to @campaign, notice: 'Card charged successfully.' else render :new end end 我的方
def create
@donation = @campaign.donations.create(donation_params)
if @donation.save_with_payment
redirect_to @campaign, notice: 'Card charged successfully.'
else
render :new
end
end
我的方法是这样的
def save_with_payment
customer = Stripe::Customer.create(
:email => email,
:card => stripe_token
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => donation_amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
end
我从其他人的例子中注意到Stripe有一个
rescue Stripe::error
rescue Stripe::InvalidRequestError => e
但我不知道如何抓住这些错误,然后将其放入通知中。您可以这样做,假设“使用付款保存”是一个回调(我假设在创建之前或保存之前)
你想怎么处理?您是否希望
随付款保存\u
表示其验证失败?另外,您有一个实例方法,而不是类方法。很抱歉,这里混淆了我的方法,感谢您的澄清。我想处理save_with_payment中的错误,并通过通知(如果可能)向用户显示错误。因此,您可能希望拆分save with payment以调用其他两种方法,一种用于客户,另一种用于收费,这样您就可以在一种方法中挽救与客户相关的错误,而在另一种方法中挽救与收费相关的错误
def save_with_payment
customer = Stripe::Customer.create(
:email => email,
:card => stripe_token
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => donation_amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::error => e
errors[:base] << "This donation is invalid because #{e}"
rescue Stripe::InvalidRequestError => e
errors[:base] << "This donation is invalid because #{e}"
end
rescue Stripe::InvalidEmailError => e
errors.add(:email, e)
end