I’m creating a series of objects on the fly using transaction and exception handling. Right now it handles the rollback and everything as expected but my rescue block doesn’t attempt to render the action I tell it to.
Here’s my code that handles the transaction
def post_validation
ActiveRecord::Base.transaction do
begin
params[:users].each do |user|
#process each user and save here
end
redirect_to root_path #success
rescue ActiveRecord::RecordInvalid
# something went wrong, roll back
raise ActiveRecord::Rollback
flash[:error] = "Please resolve any validation errors and re-submit"
render :action => "validation"
end
end
end
What’s expected upon failure: Rolls back transaction and renders the action “validation”.
What’s happening upon failure: Rolls back transaction and attempts to render the view “post_validation” which doesn’t exist.
Well it looks like there’s a few things wrong with the code I provided. For starters you don’t need to bother with the
raise ActiveRecord::Rollbackline, Rails does this behind the scenes when an exception is thrown inside of a transaction block. In addition the transaction block needed to be inside of the begin block. So the resulting code looked something like this: