Learn Ruby on Rails Book

Basics of Ruby on Rails routing

How Rails routing works

Open config/routes.rb and add the following line.

1get "/articles" => "articles#list"

Now when a user visits http://localhost:3000/articles then Rails will read config/routes.rb and Rails will start looking for any pattern matching /articles. In this case we have only one entry and Rails will find a match.

Then Rails will see articles#list. Here Rails will split that string into two parts - articles & list. articles means invoke controller named ArticlesController and list means in that controller invoke action named list.

Let's take another example.

1get "/books" => "books#list"

Here if the request is made to /books then Rails will send the request to BooksController and action would be list.

Dynamic Segments in Routes

Let's say that we want to see the details of the book The Fountainhead.

The URL could look like http://localhost:3000/books/the-fountainhead. What should the route configuration be for this? We can have something like this.

1get "/books/the-fountainhead" => "books#the_fountainhead"

We have thousands of books so this strategy will not scale. We can't keep making an entry in the routes file for each book. What we want is a way to tell Routes that the name of the book will change dynamically.

Rails routes documentation calls it Dynamic Segment. Here is how the routes will be if we use "Dynamic segment" approach.

1get "/books/:id", => "books#show"

In the above case when user visits /books/the-fountainhead then Rails will send the request to BooksController and will invoke action show. However show action needs to know what the name of the book is. Rails will make that available in params variable. params is like a hash.

In this case the show action might look like this.

1class BooksController < ApplicationController
2  def show
3    book_name = params[:id]
4    # get the book details from the database
5  end
6end

Root url

Root URL dictates what the user should see when a user is at the root url. When a user visits the site we need to send the user to somewhere. For our case the root url will be http://localhost:3000 in the development mode.

1root to: "home#welcome"

In the above case when user visits http://localhost:3000 then Rails will send that request to HomeController and action will be welcome.

More about Rails Routing in the official guide

There is a lot more to explore in Rails routing. The official Rails guide on Rails routing has some excellent material on it.

Here are some must reads.

We are not going to check in any changes done in config/routes.rb file. So let's ask git to reset the routes file.

1git checkout -f config/routes.rb