I'm trying to reduce the if statements and simplify this create action.
def create
@order = Order.create_from_result(JSON.parse(params['order']), JSON.parse(params['customer']))
# Ensure order saves before processing payment
if @order.persisted?
# Braintree transaction
result = @order.make_payment(params[:payment_method_nonce])
if result.success?
@order.paid!
@order.process!
render :json => { :status => 200 }
else
p "#Error: #{result.message}"
render :json => { :error => "#{result.message}" }
end
else
p "Error: Order did not save successfully"
render :json => { :error => "Something went wrong. Don't worry, no transaction was made." }
end
end
I thought about moving most of this logic to a single @order.process!
call, but then I'm not sure of the best way to handle the Braintree transaction result & return any errors.
Basically, three things take place in this action for an @order
:
- Order is created from JSON result
- Order payment is made
- Order is processed (order data is crunched and sent to supplier)