Recognize routes in rails console Session

sent-hil picture sent-hil · May 6, 2010 · Viewed 30.3k times · Source

Say I have a router helper that I want more info on, like blogs_path, how do I find out the map statements behind that in console.

I tried generate and recognize and I got unrecognized method error, even after I did require 'config/routes.rb'

Answer

Mike Blyth picture Mike Blyth · Dec 22, 2010

There is a good summary with examples at Zobie's Blog showing how to manually check URL-to-controller/action mapping and the converse. For example, start with

 r = Rails.application.routes

to access the routes object (Zobie's page, a couple years old, says to use ActionController::Routing::Routes, but that's now deprecated in favor of Rails.application.routes). You can then check the routing based on a URL:

 >> r.recognize_path "/station/index/42.html"
 => {:controller=>"station", :action=>"index", :format=>"html", :id=>"42"}

and see what URL is generated for a given controller/action/parameters combination:

 >> r.generate :controller => :station, :action=> :index, :id=>42
 => /station/index/42

Thanks, Zobie!