我正在学习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
答案 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条记录,则框架假设您已更新版本或删除了另一个线程中的对象。