Introduction to the Routing System in Rails

2 min read
💡
This post is part of my handbook on the Rails Router.
The Rails Router
Everything you need to know about the incredible routing system in Rails.

In its essence, the routing system in Rails determines which code (specifically, an action method in a controller class) to execute when it receives an incoming HTTP request.

But how does a router map incoming URLs to controller actions?

First, you define the routes for your application in the config/routes.rb file. It's a plain Ruby file containing a specific domain specific language (DSL) that maps URL patterns to corresponding controller actions. The Rails router uses these rules to build out the routes and figure out where to direct the request.

Each route in the routes file specifies a pattern that the router will use to match incoming URL and also to generate a URL. The route can contain dynamic segments as variable placeholders.

Here's a simple route:

# config/routes.rb

get "courses/:title" => "courses#show"

This simple route consists of a few different components.

  1. get : HTTP verb
  2. courses/:title: URL pattern
  3. :title: Dynamic segment (placeholder)
  4. courses: Controller name (CoursesController)
  5. index: Action name (show)

The above route tells the Rails router to direct any requests to courses/:title, where :title can be any string, such as courses/hello, courses/ruby, etc. The router redirects this request to the show action method on the CoursesController class.

A route must contain enough information to match an existing incoming URL and to generate a new URL. Additionally, Rails uses specific conventions that let you concisely express the common route patterns, as we'll explore later.

That's it for today. Tomorrow, we will explore and understand the routes.rb file.


That's a wrap. I hope you found this article helpful and you learned something new.

As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.

If you'd like to receive future articles directly in your email, please subscribe to my blog. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.