Forum: Ruby on Rails Implementing Optimistic Offline Lock - How ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Gernot K. (Guest)
on 2006-04-11 14:57
I understand that ActiveRecord supports the "optimistic offline
lock"-pattern through magic fields (created_at, updated_at). However, a
scaffolded CRUD-Controller doesn't generate the necessary code to
support this feature (the model state gets lost between two action
calls).

What is the best practice to prevent users from overwriting objects with
outdated data ?
Wilson B. (Guest)
on 2006-04-11 19:47
(Received via mailing list)
On 4/11/06, Gernot K. <removed_email_address@domain.invalid> wrote:
> I understand that ActiveRecord supports the "optimistic offline
> lock"-pattern through magic fields (created_at, updated_at). However, a
> scaffolded CRUD-Controller doesn't generate the necessary code to
> support this feature (the model state gets lost between two action
> calls).
>
> What is the best practice to prevent users from overwriting objects with
> outdated data ?
>

Actually, it's via the "lock_version" column.  created_at and
updated_at just handle timestamping.

Create an integer column in your table, and give it a default value of
0 (important).  Optimistic locking will be enabled automatically.
If you have a legacy table or a specific naming convention, you can use:
class Example < ActiveRecord::Base
  set_locking_column :some_other_name
end
..to override the 'magic' name.

It should work fine with scaffold code.  If you need specific handling
or a particular message when the lock stops some activity from
happening, you should rescue StaleObjectError in your controller.

def some_action
  begin
    @whatever.save!
    flash[:notice] = "All systems go."
  rescue StaleObjectError
    flash[:error] = "Someone else is already using this thingy."
  end
end

--Wilson.
This topic is locked and can not be replied to.