Rails: common approach for handling exceptions in restful actions on objects that have been destroye
- by Greg
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:
catch the exception and recover gracefully
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.