我经常遇到一种情况,即想要一次性更新多条记录,就像GMail设置多个邮件为“已读”或“未读”一样。
Rails鼓励使用ActiveRecord类上的“update”方法 - Comment.update(keys, values)
例如 - http://snippets.dzone.com/posts/show/7495
这是非常好的功能,但很难映射到restful路由。 从某种意义上说,我希望在集合上看到一个:put操作。 在路由中,我们可以添加类似以下内容的东西:
map.resources :comments, :collection => { :update_many => :put }
在表单中,你需要这样做...
<% form_for @comments do |f| %>
...
这种方法存在多个问题。如果你这样写::collection => { :update_many => :put },Rails会向索引操作(CommentsController#index)提交POST请求,而我希望它能够发送到“update_many”操作。相反,你可以这样写::collection => { :update_many => :post }。这样至少能够在控制器中调用正确的操作。
另外,你需要使用以下代码替换<% form for @comments ...:
<% form_for :comments, :url => { :controller => :comments, :action => :update_many } do |f| %>
这种方式可以正常工作。
但依旧不完美 - 感觉有点不按照Rails的方式来做。在集合控制器上,:post和:delete也似乎是有意义的。
我在此发帖,想看看是否有任何遗漏的设置。对于如何以RESTful的方式进行集合级别的:post、:put、:delete,还有其他想法吗?