Introduction to the Routing System in Rails

2 min read

For the past year, I've been teaching Ruby on Rails to students and professionals wanting to switch technology stacks.

One of the questions I used to have before working with any new student was where should we begin. Should I teach controllers first, or explore models, or go with a specific Rails framework, like ActiveRecord?

However, as I've gained more experience in teaching by working with more students, I've realized that learning routing is the best place to begin learning a new web application framework, whether it's Ruby on Rails, Laravel, or even ASP.NET MVC.

What's the essential function of a web application framework?

I'd say it's to take an incoming HTTP requests and deliver HTTP responses.

Even before the framework enters the picture, we need to think about where exactly the incoming HTTP request should go. That means we have to define an application's routes first.

Routes are the interaction points to your application through which the external world (browsers, API clients) interact with your application.

Whenever you visit a Rails application (or any website) in the browser, the server first identifies the route and then invokes the correct code to build the response.

Hence, I think learning routing is the first most important topic to understand when learning a web framework like Rails. Because without routes, you have no ability to interact with the web application.

In its essence, the routing system determines which controller action to execute when it receives an incoming HTTP request. It can also generate URLs dynamically for use in your application code.

But how can a router map URLs to controller actions?

The Rails router uses rules that you define 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.

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 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
  4. courses: Controller name (CoursesController)
  5. index: Action name

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 to the index action method on the CoursesController class.

A route should contain enough information to match an existing incoming URL and to generate a new URL.

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