Rails 3 link or button that executes action in con

2019-02-07 03:34发布

问题:

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:

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.

回答1:

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.