Search code examples
ruby-on-railsrubyrails-activestorage

Rails: How to lock ActiveRecords in order to avoid collisions in data trafic?


How can we lock an ActiveRecord and complete the operations on it before allowing another thread or request to make changes to the ActiveRecord?

I am building an eCommerce site which currently has a huge discount campaign. Only one unit of your product left. And many people want to buy it at the exact same time. In such scenario, I need to lock the product?


Solution

  • In Rails, you could use with_lock

    https://apidock.com/rails/ActiveRecord/Locking/Pessimistic/with_lock