Recognize routes in rails console Session

Ruby on-RailsRoutes

Ruby on-Rails Problem Overview

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'

Ruby on-Rails Solutions

Solution 1 - Ruby on-Rails

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!

Solution 2 - Ruby on-Rails

In the console of a Rails 3.2 app:

# include routing and URL helpers
include ActionDispatch::Routing
include Rails.application.routes.url_helpers

# use routes normally
users_path #=> "/users"

Solution 3 - Ruby on-Rails

Basically(if I understood your question right) it boils down to including the UrlWriter Module:

   include ActionController::UrlWriter
   => "/"

Or you can prepend app to the calls in the console e.g.:

   ruby-1.9.2-p136 :002 > app.root_path
   => "/" 

(This is all Rails v. 3.0.3)

Solution 4 - Ruby on-Rails

running the routes command from your project directory will display your routing:

rake routes

is this what you had in mind?

Solution 5 - Ruby on-Rails

If you are seeing errors like

ActionController::RoutingError: No route matches

Where it should be working, you may be using a rails gem or engine that does something like Spree does where it prepends routes, you may need to do something else to view routes in console.

In spree's case, this is in the routes file

Spree::Core::Engine.routes.prepend do

And to work like @mike-blythe suggests, you would then do this before generate or recognize_path.

r = Spree::Core::Engine.routes


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsent-hilView Question on Stackoverflow
Solution 1 - Ruby on-RailsMike BlythView Answer on Stackoverflow
Solution 2 - Ruby on-RailsNickView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSam FigueroaView Answer on Stackoverflow
Solution 4 - Ruby on-RailsPeteView Answer on Stackoverflow
Solution 5 - Ruby on-RailsMark SwardstromView Answer on Stackoverflow