Rails: common approach for handling exceptions in restful actions on objects that have been destroye

Posted by Greg on Stack Overflow See other posts from Stack Overflow or by Greg
Published on 2010-05-09T00:43:27Z Indexed on 2010/05/09 0:48 UTC
Read the original article Hit count: 254

Filed under:
|

It is very common in Rails for an objects_controller controller to have RESTful edit and destroy actions like so:

def edit
  @object = Object.find(params[:id])
end

def destroy
  @object = Object.find(params[:id])

  @object.destroy
  redirect_to :back
end

With an associated view that provides edit and destroy links like so:

<%= link_to "Edit the Object", edit_object_path(object) %>
<%= link_to "Delete", object, :confirm => 'Are you sure?', :method => :delete %>

And it is easy to blow this up. If I open two browser windows, A and B, destroy an object with the "Delete" link in browser A and then press the "Edit" link in browser B, the find() in the edit action throws an exception.

Obviously there are several ways to deal with this in the edit action:

  1. catch the exception and recover gracefully
  2. use @object = find(:first, "conditions... etc. and test the @object before going further

But seeing as this is such a common pattern, I would love to know how other folks deal with this situation.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about restful