开发者

Rails 3 link or button that executes action in controller

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 开发者_如何学JAVASpecs", :controller => :products, :action => :update_specs

However, I get the following routing error when I click on this link:

Routing Error No route matches {:action=>"update_specs", :controller=>"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.


You need to create a route for it.

For instance:

resources :products do
  put :update_specs, :on => :collection
end

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 }

Or you can use button_to instead of link_to which handles the POST method by default.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜