Everything about Rails Router

In-Depth lookout over Rails Router

Tushar Adhao
2 min readJul 30, 2022

Rails Router is a directing module that recognizes browser URLs and dispatches them to the controller actions requested. Basically, when a valid URL is entered on a browser, it will look for the exact controller and action associated with it.

Let’s take an example with a PostsController in which the home method is defined. So basically, the URL will end something like /posts/home for which a router needs to get defined. Does this lead to our next concern as to where to define it? So the routes are defined in ‘config/routes.rb’ in the Rails project directory. Let’s get back to the example so the requirement is to have the URL as /posts/home, so let’s define it in the routes file as,

config/routes.rbRails.application.routes.draw do
resources :posts
get ‘posts/home’, to: ‘posts#home’
end

So now on the terminal, the routes information can be extracted as,

terminal=>$ rake routesPrefix     Verb    URI Pattern           Controller#Actionposts      GET     /posts(.:format)      posts#index
POST /posts(.:format) posts#create
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
posts_home GET /posts/home(.:format) posts#home

The router automatically maps the request from the browser to the home action/method of the posts_controller.rb. The action then determines which page it should render to the user. In our case is the home.html.erb.

Rails Routes is a huge topic to cover in a single section as there are tons of subsections to it. Just to make it simpler, let’s divide it into pieces as below,

  1. Basic Routing with RESTful Design for Rails
  2. Customizing Rails Routes
  3. Constraints in Rails Routes
  4. Namespace vs Scope in Rails Routes
  5. Member vs Collection in Rails Routes
  6. DRY Rails Routes

With that separation done, let’s begin exploring each topic separately!

--

--

Tushar Adhao

Software artist spreading nuggets of coding gold and sometimes philosophy too.