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…
This can be a workaround:
Create a named resource:
map.toCSV 'logs\toCSV', :controller => :logs, :action => :toCSVI am really sorry i forgot to mention the main point!
In your view it should be:
link_to 'Export to CSV', toCSV_pathAlso, these named routes come in handy especially when you have authentication involved. For instance, during signup, rather than directing the user to
\user\newyou can direct him to\signup. Its more friendly.Thats it!!
Its simpler and it works. Cheers! 🙂