2010-07-07 137 views
1

我试图只路由一个http动词。说我有一个评论资源,像这样:在Rails中路由HTTP动词

map.resources :comments 

,并希望能够通过发送DELETE /comments要求销毁所有意见。即我希望能够只映射http动词,而不需要路由的“动作名称”部分。这可能吗?

干杯

回答

2

你可以这样做:

map.resources :comments, :only => :destroy 

产生类似的路线如下(你可以用rake routes验证)

DELETE /comments/:id(.:format) {:controller=>"comments", :action=>"destroy"} 

但需要注意的是REST风格的破坏设计用于删除特定记录不是全部 r ecords,所以这条路线仍然期待:id参数。黑客可能会传递一些哨兵价值:id代表你的应用程序上下文中的“全部”。另一方面,如果您的评论属于另一个模型,那么删除其他模型也会/应该删除评论。这通常是如何正常发生多行删除的。

+0

在这种情况下,意见的资源只是虚构的^^有真应了办法做到这一点,就像默认的“删除”路线呢... – 2010-07-07 10:41:09

1

由于这不是标准的REST风格,您需要使用自定义路由。

map.connect '/comments', 
    :controller => 'comments', 
    :action => "destroy_all", 
    :conditions => { :method => :delete } 

在你的控制器:

class CommentsController < ApplicationController 
    # your RESTful actions here 

    def destroy_all 
    # destroy all your comments here 
    end 
end 

考虑,调用是这样的:

<%= link_to "delete all comments", 
     comments_path, 
     :method => :delete, 
     :confirm => "Are you sure" %> 

PS。我没有测试这个代码,但我认为它应该工作。

+0

不会这个动作最好只与 加入map.resources:comments,:collection => {:destroy_all =>:delete} 我觉得只是删除'收集资源将更'RESTful' ... 感谢您的回复:) – 2010-07-07 11:21:39

+1

使用:collection属性会将URL生成为/ messages/delete_all,并且根据问题是不可取的。 – 2010-07-07 11:27:22