Search code examples
ruby-on-railsrubypostgresqlactiverecordsidekiq

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


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?


Solution

  • 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.