rails block a record for change for another places in the code

105 Views Asked by At

I have a ruby on rails application with a lot of sidekiq workers. Some of workers can work for a while (at least few minutes).

How can I block some record for changes from another places (ie controllers), to avoid data conflict when I save this record in the worker?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to lock the model:

account = Account.first

account.with_lock do
  # This block is called within a transaction,
  # account is already locked.
  account.balance -= 100
  account.save!
end

You can read more about it here.