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

时间:2015-02-25 20:41:56

标签: ruby-on-rails ruby rails-activerecord optimistic-locking

我正在学习rails,并阅读乐观锁定。我已将lock_version类型的integer列添加到我的articles表格中。

但是现在每当我第一次尝试更新记录 时,我都会遇到StaleObjectError例外。

这是我的迁移:

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

当我尝试通过rails console更新文章时:

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

1 个答案:

答案 0 :(得分:8)

您必须将所有文章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) 

如果查询返回更新的0条记录,则框架假设您已更新版本或删除了另一个线程中的对象。