views:

129

answers:

3

I want to have a "Delete"-link on a page viewing an object in my Ruby on Rails project. I am running into problems as

<%= link_to "Delete", @member, :confirm => 'Are you sure?', :method => :delete %>

loads the page it is on, when the method has run, thus trying to load a non-existent object. I would like to return to an index page, once the object is deleted.

Any ideas?

+2  A: 

The problem lies in your controller.

Make sure that the destroy action redirects to index and you should be fine.

If you used scaffolding to generate your controllers, this should already be done for you. Example:

class MembersController < ApplicationController
  ...

  def destroy
    @member = Member.find(params[:id])
    @member.destroy
    respond_to do |format|
      format.html{ redirect_to members_url}
      format.xml { head :ok}
    end
  end
end
EmFi
A: 

how is the destroy method on your controller ?

Lucas
+1  A: 

In my projects, I tend to create a before_filter in my controller which finds the object, and if it doesn't exist, it will automatically redirect back to a default index URL with an error message, like so:

def find_object
  @object = Object.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
  flash[:error] = "Sorry, that object was not found. Please try again."
  redirect_to objects_path
end

You'll still need to have a redirect after an object is destroyed in the controller, but at least this saves from users accidentally trying to delete/view objects that don't exist, and throwing an exception.

Josh
This is a good practice, just be sure to use sensible only/except options when activating the filter.
EmFi