Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::Base.transaction with Nested transactions

I got a rails application ( Rails v4.2.4 and Ruby v2.2.2) that some times works magically wrong .. so, let's try to explain what happens.

For some reason, not constant my records are duplicated in fraction of seconds, him just duplicate the transaction and persists a duplicated recording

I would like to know if someone of you 'masters' having pass for this situantion.

The problem do not occur every time, what means to me the error is not on my code, because the spec's are satisfing.

I have being read a lot of documentation and got a suspect "ActiveRecord::Base.transaction" with Nested transactions ... but even on my hardests trying I can't reproduce the error, what really makes me confuse and upseted

I'm asking for help ! rs ..

like image 300
Eduardo Rocha Avatar asked May 01 '26 07:05

Eduardo Rocha


1 Answers

Okay. First thing first, if you don't want to have duplicate records in the base then you should add database constraints. Go through this link to understand better. Database constraints are the first step to avoid having duplicate data.

Now ActiveRecord::Base.transaction is generally used when you want to create/update two or more unrelated objects in a single call. You want all of them to succeed else do nothing. As when you are creating a single object all the callbacks are wrapped inside a transaction by default so you need not to add ActiveRecord::Base.transaction block in that case.

More advance way is to use ActiveRecord::Locking. This technique is particularly essential when you are dealing with financial data.

To reproduce the error just send two curl requests at the same time.

like image 172
Akshay Goyal Avatar answered May 02 '26 22:05

Akshay Goyal