Rails - 乐观锁定总是触发 StaleObjectError 异常

Rails - Optimistic locking always fires StaleObjectError exception

我正在学习rails,并阅读了乐观锁。我已将类型为 integerlock_version 列添加到我的 articles table.

但现在每当我第一次尝试更新记录时,我都会得到StaleObjectError异常。

这是我的迁移:

class AddLockVersionToArticle < ActiveRecord::Migration
  def change
    add_column :articles, :lock_version, :integer
  end
end

当我尝试通过 rails 控制台更新文章时:

article = Article.first
=> #<Article id: 1, title: "Ccccc", text: "dfdsfsdfsdf", created_at: "2015-02-20 21:58:45", updated_at: "2015-02-25 20:03:12", lock_version: 0>

我也是:

article.title = "new title"
article.save

我明白了:

(0.3ms)  begin transaction
   (0.3ms)  UPDATE "articles" SET "title" = 'dwdwd', "updated_at" = '2015-02-25 20:40:36.537876', "lock_version" = 1 WHERE ("articles"."id" = 1 AND "articles"."lock_version" = 0)
   (0.1ms)  rollback transaction
ActiveRecord::StaleObjectError: Attempted to update a stale object: Article

您必须将所有文章 lock_version 初始化为 0。 查看查询:

UPDATE "articles" SET "title" = 'dwdwd', "updated_at" = '2015-02-25 20:40:36.537876', "lock_version" = 1 WHERE ("articles"."id" = 1 AND "articles"."lock_version" = 0)
       (0.1ms) 

如果查询returns0条记录更新,那么框架假设你更新了版本或者删除了另一个线程中的对象。