【问题标题】:does with_lock lock everything inside the block?with_lock 会锁定块内的所有内容吗?
【发布时间】:2020-10-19 16:28:23
【问题描述】:

with_lock 是锁定块中的所有模型还是仅锁定模型本身?例如以下是with_lock 中的所有item 模型被锁定还是只是entry 模型被锁定?

class Entry < ApplicationRecord
  enum state: [:pending, :posted]
    
  has_many :items, dependent: :destroy
 
  def post!
    with_lock do
      return unless pending?
      items.each { |i| i.post! }
      self.posted!
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord locking pessimistic-locking


    【解决方案1】:

    with_lock 在单个实例上获得行级悲观锁。 with_lock简单地将锁和事务语句合二为一,所以相当于:

    Entity.transaction do
      entity_instance.lock!
    end
    

    你在模型中调用with_lock,所以你实际上是在调用self.with_lock。也就是说,您正在获得对Entity 的当前实例的锁定。除非您也明确锁定它们,否则单个 Item 记录不会被锁定。不过,对它们的更改确实包含在同一个父事务中。

    【讨论】:

    • 这很清楚,完美地回答了我的问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2017-07-29
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多