Can someone clear up nested transactions?


#1

I simply can’t find a straight answer on this anywhere. If I have the
need of nested transactions do I need to do this

Article.transaction

my_article = Article.new(:title => ‘This is a new title’, :content
=> ‘This is some new content’)
my_article.save

Comment.transaction

my_comment = Comment.new(:article => my_article, :body => 'This is

the body of my comment’)
my_comment.save

CommentConfirmation.transaction

  my_conf = CommentConfirmation.new(:commnet =>

my_comment, :confirmed => true)
my_conf.save

end

end

Vote.transaction

my_vote = Vote.new(:article => my_article, :rank => 5)
my_vote.save

end

end

or does

Article.transaction

my_article = Article.new(:title => ‘This is a new title’, :content
=> ‘This is some new content’)
my_article.save

my_comment = Comment.new(:article => my_article, :body => ‘This is
the body of my comment’)
my_comment.save

my_conf = CommentConfirmation.new(:commnet => my_comment, :confirmed
=> true)
my_conf.save

my_vote = Vote.new(:article => my_article, :rank => 5)
my_vote.save

end

do the same thing?

Also, does create work the same as save, in terms of transactions, so
if I do something like

Article.transaction

my_article = Article.new(:title => ‘This is a new title’, :content
=> ‘This is some new content’)
my_article.save

Comment.transaction

my_comment = Comment.new(:article => my_article, :body => 'This is

the body of my comment’)
my_comment.save

end

end

is that the same as

Article.transaction

my_article = Article.create(:title => ‘This is a new
title’, :content => ‘This is some new content’)

Comment.transaction

my_comment = Comment.create(:article => my_article, :body => 'This

is the body of my comment’)

end

end

Dale


#2

The short answer to your question is yes, all the examples you gave
above are equivalent: they would each roll back under the same
cicumstances and leave the DB in the same condition. Nesting
transactions in Rails almost never has an effect. I was going to
give a more complete explanation, but it got sort of unreadable so I
posted it here:
http://expectedbehavior.com/articles/2007/05/29/nested-transactions-in-rails

Hopefully that’s enough to clear things up for you.

Matt


#3

Hi,

how can I span a transaction over two or more unrelated tables?
Is there a generic way to start a transaction on a not per-only-one-
model basis, so that I can change rows in different tables and a
rollback rolls back allchanges in all unrelated tables?
So the sould would not be “MyModel.transaction…” but something like
“transaction…”

thanks,
Alex.