Rails 3链接或按钮在控制器中执行操作 [英] Rails 3 link or button that executes action in controller
问题描述
在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}
Routing Error No route matches {:action=>"update_specs", :controller=>"products"}
我已经阅读了路由,但我不明白为什么我应该路由这个方法,如果所有其他方法都可以通过资源访问:产品。 / p>
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
而不是默认处理 POST
方法的 link_to
。
Or you can use button_to
instead of link_to
which handles the POST
method by default.
这篇关于Rails 3链接或按钮在控制器中执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!