问题描述
在 RoR 3 中,我只想有一个链接/按钮来激活控制器中的某些操作/方法.具体来说,如果我点击页面上的update_specs"链接,它应该转到我的产品控制器中的update_specs"方法.我在此网站上找到了执行此操作的建议:
In RoR 3, I just want to have a link/button that activates some action/method in the controller. Specifically, if I click on a 'update_specs' link on a page, it should go to 'update_specs' method in my products controller. I've found suggestions to do this on this site:
link_to "Update Specs", :controller => :products, :action => :update_specs
但是,当我单击此链接时出现以下路由错误:
However, I get the following routing error when I click on this link:
路由错误没有路由匹配 {:action=>"update_specs",:controller="products"}
我已经阅读了路由,但我不明白如果所有其他方法都可以通过 resources:products 访问,我为什么必须路由这个方法.
I've read up on routing but I don't understand why I should have to route this method if all other methods are accessible via resources:products.
推荐答案
您需要为其创建路由.
例如:
resources :products do
put :update_specs, :on => :collection
end
默认情况下,link_to
会在你的路由中寻找 GET
方法.如果要处理 POST
或 PUT
方法,则需要通过添加 {:method =>:post }
或 {:method =>:put }
作为参数,如:
Also by default link_to
will look for a GET
method in your routes. If you want to handle a POST
or PUT
method you need to specify it by adding {:method => :post }
or {:method => :put }
as a parameter, like:
link_to "Update Specs", {:controller => :products, :action => :update_specs}, {:method => :put }
或者您可以使用 button_to
而不是 link_to
,后者默认处理 POST
方法.
Or you can use button_to
instead of link_to
which handles the POST
method by default.
这篇关于在控制器中执行操作的 Rails 3 链接或按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!