Checking named routes in irb console

ruby rails

Wed Apr 29 08:48:44 -0700 2009

I tend to use named routes in my link_to, link_to_remote, remote_form_for etc prototype helpers, so that my action paths in the view always conform to the declarations in routes.rb and so it’s expressive.

Say for example, here’s a namespaced & named route snippet in routes.rb:

map.namespace :researcher do |researcher|
  researcher.resources :projects
end

Now rails is of course nice to respond all your CRUD actions associated with projects, namespaced under researcher as far as the controller is concerned. Note, this also implies that I have a Project model. But I often run into guessing what URI the named routes generate and this is where irb comes in really handy.

  • Fire up the console

    $ script/console
    

  • I want to see what path for a new project looks like

    >> app.new_researcher_project_path
    "/researcher/projects/new"
    

  • I want to see what the edit path for an existing project looks like

    >> app.edit_researcher_project_path(Project.find(:first))
    "/researcher/projects/1/edit"
    

Compartmentalizing resources by namespaces is very handy for a large projects but the named routes can get really hairy in no time and so this is really useful. You can also use:

rake routes
& filter what you’re looking for of course, but if you find yourself hours on end working on the console, this is a big big convenience.

blog comments powered by Disqus