Rails - Optimistic lock always throws StaleObjectError exception

I study rails and read about optimistic blocking. I added an integer lock_version column to the articles table.

But now, when I try to update the record for the first time , I get a StaleObjectError exception.

Here is my migration:

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

When I try to update an article through the 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> 

And I:

 article.title = "new title" article.save 

I get this:

 (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 
+5
source share
1 answer

You should initialize all lock_version articles to 0. Look at the query:

 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) 

If the query returns 0 updated records, then the structure assumes that you have updated the version or deleted the object in another thread.

+8
source

Source: https://habr.com/ru/post/1214195/


All Articles