Siwei
Siwei

Reputation: 21557

What's the difference between ModelA.transaction do ..end and ModelB.transaction do ..end in Rails?

I have two models(ActiveRecord), ModelA and ModelB. I am wondering is the same for the two code segment show as below?

ModelA.transaction do 
    ModelA.create! attr1: 'value1', attr2: 'value2'
    ModelB.create! attr1: 'value1', attr2: 'value2'
end

ModelB.transaction do 
    ModelA.create! attr1: 'value1', attr2: 'value2'
    ModelB.create! attr1: 'value1', attr2: 'value2'
end

It seems that both of them working well. so what's the difference between them?

thanks

Upvotes: 0

Views: 94

Answers (1)

tessie
tessie

Reputation: 1032

There is no difference. Transactions are per database connections not not per model. So both of them are equal provided class are mapped to same database.

Reference: https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

Upvotes: 2

Related Questions