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
and Rails will start looking for any pattern matching
In this case we have only one entry and Rails will find a match.
Then Rails will see
Here Rails will split that string into two parts -
articles means invoke controller named
list means in that controller invoke action named
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
Let's say that we want to see the details of the book The Fountainhead.
The URL could look like
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
BooksController and will invoke action
show action needs to know what the name of the book is.
Rails will make that available in
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 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
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
So let's ask git to reset the routes file.
1git checkout -f config/routes.rb