Implementing Optimistic Offline Lock - How?

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 ?

On 4/11/06, Gernot K. [email protected] 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.