module ActiveRecord::Locking::Pessimistic::ConvenienceMethods

Public Instance Methods

find_and_save_atomically(id, opts = {}, &block) click to toggle source

Finds a records with the given ID, applies the block, then calls save. Returns the record.

All options are passed to save, except for:

<tt>lock:</tt> - pass an SQL locking clause to append the end of the SELECT statement, defaults to "FOR UPDATE"

Example:

Post.find_and_save_atomically(1, validate: false, lock: "FOR SHARE") {|post| post.title = "new title" s}
# File lib/active_record/locking/pessimistic/convenience_methods.rb, line 17
def find_and_save_atomically(id, opts = {}, &block)
  _find_and_apply_atomically(:save, id, opts, &block)
end
find_and_save_atomically!(id, opts = {}, &block) click to toggle source

Same as find_and_save_atomically, just calls save! on the model

# File lib/active_record/locking/pessimistic/convenience_methods.rb, line 22
def find_and_save_atomically!(id, opts = {}, &block)
  _find_and_apply_atomically(:save!, id, opts, &block)
end
find_and_update_atomically(id, attrs, opts = {}) click to toggle source

Find and update attributes, but atomically

# File lib/active_record/locking/pessimistic/convenience_methods.rb, line 27
def find_and_update_atomically(id, attrs, opts = {})
  find_and_save_atomically(id, opts) {|r| r.assign_attributes attrs }
end

Private Instance Methods

_find_and_apply_atomically(method, id, opts = {}, &block) click to toggle source
# File lib/active_record/locking/pessimistic/convenience_methods.rb, line 33
def _find_and_apply_atomically(method, id, opts = {}, &block)
  kind = opts.delete(:lock) || true
  transaction do
    record = lock(kind).find(id)
    block.call(record)
    record.send(method, opts)
    record
  end
end