Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 697
heebee313 Avatar asked Sep 26 '11 17:09

heebee313


1 Answers

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.

like image 90
Amokrane Chentir Avatar answered Oct 23 '22 01:10

Amokrane Chentir