使用Stripe并希望: 1.检查模型验证 2.如果没有错误处理卡令牌。 3.如果卡有效,则保存新记录。
下面我介绍它首先处理卡片,然后如果成功,则保存记录。不幸的是,该记录可能无法通过验证,但该卡已经收费。
作为一个黑客,我在视图中有一个js验证(镜像模型验证),不允许在满足条款之前提交表单。
Tourregistration.rb控制器
def create
token = params[:tourregistration][:stripeToken]
begin
charge = Stripe::Charge.create(
:amount => (params[:tourregistration][:invoice].to_d*100).round,
:currency => "usd",
:source => token,
:description => "Example charge"
)
rescue Stripe::CardError => e
# The card has been declined
redirect_to :back, :notice => "#{e}"
else
@tourregistrations = tourregistration_data.map do |tourregistration_params|
Tourregistration.new(tourregistration_params)
end
@tourregistrations.each(&:save)
if @tourregistrations.all?(&:valid?)
flash[:notice] = 'Sign-up Complete'
redirect_to root_url
else
redirect_to :back, :notice => "Something went wrong. Please fill in all fields."
end
end
端
Tourregistration.rb模型
class Tourregistration < ActiveRecord::Base
belongs_to :patron
belongs_to :tour
has_one :referrer
validates :fname, length: { minimum: 2}
validates :lname, length: { minimum: 2}
validates :email, presence: true
validates :price, presence: true
validates :invoice, presence: true
validates :patron_id, presence: true
validates :tour_id, presence: true
end
答案 0 :(得分:2)
Other than callbacks, you can use a database transaction, for example :
ActiveRecord::Base.transaction do
results = @tourregistrations.map(&:save) # validate and save the records
raise ActiveRecord::Rollback if results.any?{|result| result == false } # rollback the transaction if any registration failed to be saved
payment = charge_card # process the payment
raise ActiveRecord::Rollback unless payment # rollback if payment failed
end
As a side note, this kind of logic is a textbook example for a service object.