开发者

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

开发者 https://www.devze.com 2023-01-20 08:14 出处:网络
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?

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 tr开发者_如何学编程ansaction, because ActiveRecord can only handle one connection, thus it should not matter. Is that correct?

Thanks, Alex.


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.


Absolutely right. From the Rails API docs:

Though the transaction class method is called on some Active Record class, the objects within the transaction block need not all be instances of that class. This is because transactions are per-database connection, not per-model.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号