Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Optimistic locking always fires StaleObjectError exception

I'm learning rails, And read about optimistic lock. I've added lock_version column of type integer into my articles table.

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

Here's my migration:

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

When I try updating an article through 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 do:

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
like image 570
Rafael Adel Avatar asked Feb 25 '15 20:02

Rafael Adel


Video Answer


1 Answers

You have to initialize all the articles lock_version 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 records updated, then the framework suppose that you have updated the version or deleted the object in another thread.

like image 100
eritiro Avatar answered Oct 21 '22 12:10

eritiro