Pessimistic locking in Rails

0

https://dev.to/nodefiend/rails-pessimistic-locking-45ak

  • Locking::Pessimistic provides support for row-level locking
Account.lock.find(1)
  • Start a transaction and lock at the same time by calling with_lock with a block
class JournalEntry < ApplicationRecord  

  def post!
    with_lock do
      return unless pending? and balanced?
      items.each { |i| i.post! }
      self.posted_at = Time.current; self.posted!
    end
  end

end

https://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html

Calling lock with a find query is all that is needed to use pessimistic locking in Rails.

Toy.lock.find_by(name: 'racecar')

The above code will lock the racecar Toy until the end of the transaction. Calling lock outside of a transaction will only lock the record for the single call.

http://www.brianmehrman.com/blog/2018/05/29/optimistic-vs-pessimistic-locking/

Decent tutorial and code

https://github.com/gorails-screencasts/pessimistic-locking-with-rails/blob/master/app/models/coupon.rb

  • 0 posts
  • 0 subtopics
  • 8 days ago by vince