ohana
ohana

Reputation: 6751

ruby on rails adding new route

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

Upvotes: 0

Views: 2726

Answers (3)

Shripad Krishna
Shripad Krishna

Reputation: 10498

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! :)

Upvotes: 1

Salil
Salil

Reputation: 47532

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.

Upvotes: 2

Jonathan Julian
Jonathan Julian

Reputation: 12272

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.

Upvotes: 0

Related Questions