How to make Rails ActiveRecord commit a transactional flash

Is it possible to force ActiveRecord for a transaction (or just save / create)?

I have a work clock that creates tasks in the background for multiple workgroups. The problem is that the desktop of the watch sometimes creates a task and pushes it to the work task before the information of the working hours is completely cleared to db, which causes an ugly race condition.

Using the after_commit function is not really viable due to the architecture of the product and how tasks are created.

In short, I need one worker to create a task and dump this task in db.

+4
source share
1 answer

ActiveRecord uses #transactionto create a started block and either rolls back or commits a transaction. I believe this will help your problem. Essentially (the intended task is the ActiveRecord class):

Task.transaction do
  new_task = Task.create(...)
end

BackgroundQueue.enqueue(new_task)

You can also go directly to #connectionunder:

Task.connection.commit_db_transaction

This is a bit low level, and you should be pretty sure how the code is used. #after_commitis the best answer, even if it requires a bit of code conversion to work. If this does not work for sure, then these two approaches should help.

+6
source

Source: https://habr.com/ru/post/1539986/


All Articles