views:

79

answers:

3

i have an RoR application Log, which similar to the book store app, my logs_controller has all default action: index, show, update, create, delete..

now i need to add new action :toCSV, i defined it in logs_controller, and add new route in the config/routes as:

map.resources :logs, :collection => { :toCSV => :get }.

from irb, i checked the routes and see the new routes added already:

>> rs = ActionController::Routing::Routes
>> puts rs.routes
GET    /logs/toCSV(.:format)?                   {:controller=>"logs", :action=>"toCSV"}

then ran ‘rake routes’ command in shell, it returned:

toCSV_logs GET    /logs/toCSV(.:format)         {:controller=>"logs", :action=>"toCSV"}

everything seems working. finally in my views code, i added the following:

link_to 'Export to CSV', toCSV_logs_path

when access it in the brower 'http://localhost:3000/logs/toCSV', it complained: Couldn't find Log with ID=toCSV

i checked in script/server, and saw this one:

ActiveRecord::RecordNotFound (Couldn't find Log with ID=toCSV):
  app/controllers/logs_controller.rb:290:in `show'

seems when i click that link, it direct it to the action 'show' instead of 'toCSV', thus it took 'toCSV' as an id...anyone know why would this happen? and to fix it? Thanks...

A: 

Remove the map.resources line from routes.rb, and then run rake routes. If you see a route /logs/:id, that is the route that should probably be removed.

Jonathan Julian
+1  A: 
map.resources :logs, :collection => { :toCSV => :get }

I think this is perfect. you must restart your server evry time you change the config/routes.rb It's no answer though but it's important.

Salil
If you are running webrick you don't need to restart your server after changing routes.
Sohan
If you're running in the *development* environment you dont need to restart the server
Ryan Bigg
A: 

This can be a workaround: Create a named resource:

map.toCSV 'logs\toCSV', :controller => :logs, :action => :toCSV

I am really sorry i forgot to mention the main point!

In your view it should be:

link_to 'Export to CSV', toCSV_path

Also, these named routes come in handy especially when you have authentication involved. For instance, during signup, rather than directing the user to \user\new you can direct him to \signup. Its more friendly.

Thats it!!

Its simpler and it works. Cheers! :)

Shripad K
this one works, thanks! :)
ohana
You are welcome :)
Shripad K