我做错了什么回复:Rails with_lock?

am I doing something wrong re: Rails with_lock?

对于从 4.2 到 5.1.7 的 Rails 版本,下面的代码工作正常。

在 Rails 5.2 中,在我的 Rspec 测试中,除非我添加额外的 reload(如下所示作为注释),否则它会失败,但例外情况是:

ActionView::Template::Error:
  Locking a record with unpersisted changes is not supported. 
  Use `save` to persist the changes, or `reload` to discard them explicitly.

因为 with_lock 之前的调用是 save(根据异常消息)为什么这仍然会触发异常,除非在 reload 之后立即添加额外的 reload save?

  # merge into the serialized hash field 'settings' a new hash
  def update_settings(hash)
    return if hash.class != Hash
    return if !hash || (hash.count == 0)

    self.save # flush any pending changes
    # self.reload # <<<<< WHY MUST THIS BE added for rails 5.2?
    self.with_lock do
      mysettings = self.reload.settings
      # mysettings = self.settings
      hash.each do |k, v|
        mysettings[k] = v
      end
      self.update_attribute :settings, mysettings
    end
  end

我猜 self.save 失败了。您应该在调用 self.save 之后打印 puts self.errors.full_messages 以查看原因。或者您可以将 save 替换为 save!.