开发者

Named routes: why destroy_message_path doesn't work?

I am having a link like

  <a href = '/messages/destroy/<%= @showmessage.id %>'>Delet开发者_开发百科e Message</a>

I am rewriting this into

  <%= link_to "Delete Message", destroy_message_path(:id => "1") %>

In my routes i have

   map.resources :messages, :collection => { :destroy => :get }

And in my controller

   def destroy
     @message = Message.find(params[:id])
     @message.destroy
     redirect_to :action => 'index'
   end

When I run the page, I am getting the error as:

 undefined method `destroy_message_path' for #<ActionView::Base:0xb24a24c0>

How do I resolve this?


I'm not sure if you mean to be fighting against the Rails conventions here, but its alot easier to go along with them, so if you are ok with that you can do the following:

Remove this from your routes:

map.resources :messages, :collection => { :destroy => :get }

Change it to:

map.resources :messages

And use this link format instead:

<%= link_to "Delete Message", message_path(:id => "1"), :method => 'delete' %>

The URL for the destructive action will look like /messages/1, but the "method" portion of that link_to method will make Rails create a hidden form and perform a simulated "DELETE" action against the URL. Which is far more RESTful, and follows along with what Rails is expecting you to do.


With resources, you shouldn't be making a GET request, you should be making a DELETE request like this:

<%= link_to "Delete Message", destroy_message_path(:id => "1"),
            :confirm => 'Are you sure?', :method => :delete %>

and in your routes file:

map.resources :messages

On another note, you can just pass in the object of the message to destroy_message_path, so for example:

<%= link_to "Delete Message", destroy_message_path(@message),
            :confirm => 'Are you sure?', :method => :delete %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜