我正在学习Rails,并阅读有关乐观锁的内容。我已经在我的articles
表中添加了类型为integer
的lock_version
列。
但是现在,每当我尝试第一次更新记录时,就会出现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