Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails transaction: does it matter on which ActiveRecord model class?

When I have 2 objects to save inside a transaction

a = A.new(...)  
b = B.new(...)

Does it matter on which model class I invoke the transaction method?

A.transaction do
  a.save
  b.save
end

or

B.transaction do
  a.save
  b.save
end

IMNO both use the same db transaction, because ActiveRecord can only handle one connection, thus it should not matter. Is that correct?

Thanks, Alex.

like image 226
agreif Avatar asked Oct 19 '10 08:10

agreif


1 Answers

Yes, you are correct provided both classes use the same database connection. It is possible for a class to use establish_connection to connect to a different database but you would know if you were doing that. So, as you correctly suggest using either A.transaction or B.transaction is fine.

If they were using different databases you could nest the transaction calls:

A.transaction do
  B.transaction do
   ...
  end
end

but that is not necessary in this case.

like image 163
Shadwell Avatar answered Nov 09 '22 09:11

Shadwell