开发者

"link_to :method => :delete" on a page viewing the the object

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开发者_StackOverflow to return to an index page, once the object is deleted.

Any ideas?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜