ruby - Check validation before save rails -
using stripe , want to: 1. check model validation 2. if no errors process card token. 3. if card works save new record.
below have processes card first, if successful, saves record. unfortunately record might fail validation card charged.
as hack have js validation (that mirrors model validations) in view doesn't allow form submitted until terms met.
tourregistration.rb controller
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 # card has been declined redirect_to :back, :notice => "#{e}" else @tourregistrations = tourregistration_data.map |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 fields." end end end
tourregistration.rb model
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
other callbacks, can use database transaction, example :
activerecord::base.transaction results = @tourregistrations.map(&:save) # validate , save records raise activerecord::rollback if results.any?{|result| result == false } # rollback transaction if registration failed saved payment = charge_card # process payment raise activerecord::rollback unless payment # rollback if payment failed end as side note, kind of logic textbook example service object.
Comments
Post a Comment