I’m building the checkout page for an e-commerce site, and I have a fairly long transaction that creates a new User model and a new Order model. I wrapped the creation of these models in a transaction so that if validation for one fails, the other isn’t hanging around in the database. Here’s the trimmed-down code in my OrdersController:
rescue_from ActiveRecord::Rollback, with: :render_new
def render_new
render action: 'new'
end
ActiveRecord::Base.transaction do
@user = User.new params[:user]
unless @user.save
raise ActiveRecord::Rollback
end
//More stuff
...
@order = Order.new params[:order]
...
unless @order.save
raise ActiveRecord::Rollback
end
end
The error I’m seeing is this:
Missing template orders/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}
I’m confused as to why its trying to render the templates orders/create and application/create instead of rendering orders/new.
Is there a better way to force the transaction to fail so that the rollback will occur?
I think the intention is a bit clearer when wrapping the transaction in a begin/rescue block.
You need to return in the
createmethod, otherwise it’s execution will continue to the end of the method and Rails default render will occur (in this case it means attempting to find acreate.___template).If you don’t like the begin/rescue block you can just add an
and returnto theraiselines