# Activerecord transaction

**URL:** <https://www.ruby-forum.com/t/activerecord-transaction/140596>\
**Category:** Rails\
**Created:** [June 16, 2008, 5:35pm UTC](https://www.ruby-forum.com/t/activerecord-transaction/140596 "2008-06-16T17:35:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ajitonrails](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ajitonrails](https://www.ruby-forum.com/u/ajitonrails)\
**Post date:** [June 16, 2008, 5:35pm UTC](https://www.ruby-forum.com/t/activerecord-transaction/140596/1 "2008-06-16T17:35:34Z")

</div>

hello all

I have one form… which provide data to three tables, 3 Models. i am  
trying to setup a transaction for save statement. seems like i am  
missing something… as this is not working properly. following is my  
code:

User.transaction do  
@user = User.new(params[:user])

```
    @user.save

    @user_details = UserDetail.new(params[:user_detail])
    @user_details.user_id = @user.id
    @user_details.save

    @user_tree = UserTree.new()
    @user_tree.user_id = @user.id
    @user_tree.save

```

end

if something goes wrong then User table is not creating new row but  
other two tables get new rows.

any suggestions.

Thanks in advance

Ajit

---

<div class="post-metadata">

**Author:** ![ajitonrails](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ajitonrails](https://www.ruby-forum.com/u/ajitonrails)\
**Post date:** [June 16, 2008, 6:16pm UTC](https://www.ruby-forum.com/t/activerecord-transaction/140596/2 "2008-06-16T18:16:14Z")

</div>

Depending on the nature of your relationships you might be able to do  
this (which has automatic transaction wrapping on the DB):

@user = User.new(params[:user])  
@user.build\_user\_detail(params[:user\_detail])  
@user.build\_user\_tree  
@user.save

If either UserDetail or UserTree uses a has\_many relationship then you  
can use @user.user\_xxxs.build(params[:user\_xxx])

---

<div class="post-metadata">

**Author:** ![ajitonrails](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ajitonrails](https://www.ruby-forum.com/u/ajitonrails)\
**Post date:** [June 16, 2008, 6:49pm UTC](https://www.ruby-forum.com/t/activerecord-transaction/140596/3 "2008-06-16T18:49:59Z")

</div>

On 16 Jun 2008, at 16:35, Ajit wrote:

> ```
> @user_tree = UserTree.new()
> @user_tree.user_id = @user.id
> @user_tree.save
> 
> ```
> 
> end
> 
> if something goes wrong then User table is not creating new row but  
> other two tables get new rows.

What are you expecting to happen? are you expecting this to rollback  
if @user.save fails? Rollback only happens if an exception is thrown,  
and save just returns false if validation fails. save! on the other  
hand throws an exception when validation fails

Fred
