# Transaction Failures

**URL:** <https://www.ruby-forum.com/t/transaction-failures/188772>\
**Category:** Rails\
**Created:** [May 18, 2010, 10:25am UTC](https://www.ruby-forum.com/t/transaction-failures/188772 "2010-05-18T10:25:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![brianp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/94ad74/32.png) [@brianp](https://www.ruby-forum.com/u/brianp)\
**Post date:** [May 18, 2010, 10:25am UTC](https://www.ruby-forum.com/t/transaction-failures/188772/1 "2010-05-18T10:25:32Z")

</div>

Hey,

I’ve got a multiple model (4) form on my site.

I have the controller handling the creation with a transaction. I do  
this because if one object can’t save I don’t want any of them saved  
and need to be able to quit the entire transaction without making any  
permanent db calls.

The problem I find is. If a validation fails on an object without the  
transaction present. The page refreshes with rails generated  
validation errors. With the transaction present I don’t know how to  
send it back to the page with errors present. But again without the  
transaction if there is a problem all good objects get saved to the db  
and the bad one does not.

So the problem is: If the transaction fails. I need the form page to  
load with validation errors.

I use the code below:

def create  
begin  
ActiveRecord::Base.transaction do  
@dealer = Dealer.new(params[:dealer])  
@dealer.save!  
@user = @dealer.users.build(params[:user])  
@user.role\_id = 3  
@dealer.addresses.build(params[:mailing\_address])  
#@dealer.addresses.create(params[:billing\_address])  
end  
rescue ActiveRecord::RecordInvalid =\> invalid  
flash[:notice] = “Vehicle was not created”  
@dealer = Dealer.new  
@user = User.new  
render :action =\> “new”  
end

```
if ! @dealer.new_record?
  flash[:notice] = "Dealer, User and addresses saved!"
  redirect_back_or_default login_path
end

```

end

cheers.

---

<div class="post-metadata">

**Author:** ![brianp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/94ad74/32.png) [@brianp](https://www.ruby-forum.com/u/brianp)\
**Post date:** [May 18, 2010, 12:15pm UTC](https://www.ruby-forum.com/t/transaction-failures/188772/2 "2010-05-18T12:15:35Z")

</div>

Found my problem immediately after posting.

In:

rescue ActiveRecord::RecordInvalid =\> invalid  
flash[:notice] = “Vehicle was not created”  
@dealer = Dealer.new  
@user = User.new  
render :action =\> “new”  
end

Should be:

rescue ActiveRecord::RecordInvalid =\> invalid  
flash[:notice] = “Vehicle was not created”  
render :action =\> “new”  
end

Creating new objects seems to get blank all the fields. As well I was  
missing separate \<%= f.error\_messages %\> for each model type.
