[Rails] Re: When to use optimistic locking?

Jason Tuttle
2006-05-09T18:18:21Z

Jason Tuttle wrote:
> Hi All,
>
> I''m having some trouble deciding when and how to implement
optimistic
> locking.
>
> Let''s say I have a multiuser Rails app, and let''s say it
stores,
> among other things "vital" customer information.
>
> The standard methods created by the Rails generate scaffold script
> look like this:
>
>    def edit
>      @customer = Customer.find(params[:id])
>    end
>
>    def update
>      @customer = Customer.find(params[:id])
>      if @customer.update_attributes(params[:customer])
>        flash[:notice] = ''Customer was successfully
updated.''
>        redirect_to :action => ''show'', :id =>
@customer
>      else
>        render :action => ''edit''
>      end
>    end
>
> What if I want to guard against 2 people simultaneously updating the
> same customer record? How would I go about doing this? I can''t
find
> any examples online, and I''m a bit lost.
>
> Thanks,
>
> : )
>
> Jason

The more I think about it, there doesn''t seem to be a way to take
advantage of Active Record''s  optimistic locking when using the
standard
scaffold generated CRUD approach because the model state is lost between
the call to "edit" and the subsequent call to "update". --
The
ActiveRecord::StaleObjectError will never be thrown.

Do you have to manually track the value of the lock_version column?

There must be a more elegant solution.

I must be missing something. I just can''t figure out what.

- Jason