Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a controller action with link_to

After playing around with links in Rails for a view hours i've managed to actually get a link to invoke a method in my controller. But i still don't understand why all my other attempts failed. Im hoping you could help me out with that.

I have the scaffold "Cars". When in the show view for a car, id like to click a link that invokes the method "drive" in my Car controller.

This WORKS: <%= link_to "Drive", drive_car_path(@car) %>

It seems this only works if i have this is my routes.rb:

resources :cars do
  member do
    get 'drive'
  end
end

Why does <%= link_to "Drive", car_path, :method => :drive %> not work?

Do I need to put a GET in the routes.rb file for every method I create in my controller?

I can't seem to find any sites explain how to use links together with routes. They only seem to come separate. Do you guys have any easily understandable tutorials on this?

like image 838
deRailed Avatar asked Nov 09 '10 16:11

deRailed


1 Answers

Try link_to "Drive", :controller => "car", :action => "drive"

Also, method is for choosing the HTTP method (GET, POST, ...). It's not method as in routine.

Be sure to check out Rails Routing from the Outside In and The Lowdown on Routes in Rails 3, they're both awesome resources.

like image 53
Julio Santos Avatar answered Sep 30 '22 02:09

Julio Santos