Forum: Ruby on Rails transaction question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dfc408d15775d88aa1a0675744cd70f6?d=identicon&s=25 jeff cole (Guest)
on 2006-03-08 00:19
How does one set up a transaction for multiple models?  For example, how
do you wrap the entire logic below in one transaction?

#begin transaction
for bar in foo.bars
  bar.something += 1
  bar.save
end

foo.something += 1
foo.save
#end transaction

For even more complexity, what if a mail notification is sent for each
bar modified in the collection?

thanks,
Jeff
337cdd270761e0e6f4356de45b04d388?d=identicon&s=25 Jonathan Viney (jonny)
on 2006-03-08 01:44
Can you do:

Bar.transaction
  foo.bars.each do |bar|
    bar.something += 1
    bar.save
  end
end

-Jonny.
Dfc408d15775d88aa1a0675744cd70f6?d=identicon&s=25 jeff cole (Guest)
on 2006-03-08 18:06
I want the change to foo wrapped in the same transaction.  I don't think
you can stick that in Bar.transaction?

-Jeff
59de94a56fd2c198f33d9515d1c05961?d=identicon&s=25 Tom Mornini (Guest)
on 2006-03-08 22:15
(Received via mailing list)
Yes,  you can.

--
-- Tom Mornini
02d93c53aa78518c45c2155f44415c1a?d=identicon&s=25 leetc (Guest)
on 2007-04-19 08:59
Hi Tom,

    How do you do it ? Jonny's example seems vague... I need both model
to be save!

Thanks.

Tom Mornini wrote:
> Yes,  you can.
>
> --
> -- Tom Mornini
This topic is locked and can not be replied to.