Searching complex Rails routes

Mastering the routes command will save you a lot of time. Here are a pro tips on how to use it.

rails routes
                                Prefix Verb     URI Pattern                                                     Controller#Action
                      new_user_session GET      /sign-in(.:format)                                              users/sessions#new {:subdomain=>"auth"}
                          user_session POST     /sign-in(.:format)                                              users/sessions#create {:subdomain=>"auth"}
                  destroy_user_session DELETE   /sign-out(.:format)                                             users/sessions#destroy {:subdomain=>"auth"}

Search your routes

To search the output, you can use -g (aka grep).

rails routes -g organization

This will return only routes that match organization.

The -g option is fairly new to Rails. Prior to this, people would commonly pipe the results to grep. Like this: rails routes | grep organization.

By controller

You can also view the routes for a single controller. To do this, use -c.

rails routes -c UsersController

Extended format

The default format sometimes be difficult to read. Try using -E for an easier to read format.

rails routes -E

--[ Route 1 ]------------------------------------------------------------------------------------------------------------------------------------------------------
Prefix            | new_user_session
Verb              | GET
URI               | /sign-in(.:format)
Controller#Action | users/sessions#new {:subdomain=>"auth"}
--[ Route 2 ]------------------------------------------------------------------------------------------------------------------------------------------------------
Prefix            | user_session
Verb              | POST
URI               | /sign-in(.:format)
Controller#Action | users/sessions#create {:subdomain=>"auth"}
--[ Route 3 ]------------------------------------------------------------------------------------------------------------------------------------------------------
Prefix            | destroy_user_session
Verb              | DELETE
URI               | /sign-out(.:format)
Controller#Action | users/sessions#destroy {:subdomain=>"auth"}

Now you don't have to remember what each column is. Useful!

What is `prefix`?

One final tip, notice prefix in route output. This is what you'll use to determine the path helper. When the prefix is user_session. This means Rails will make user_session_path and user_session_url available to you in your views and controllers.