Introduction to the Routing System in Rails
The Rails router sits at the front of every request, deciding which controller and action should handle it.
This post is part of my handbook on the Rails Router.
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.
get: HTTP verbcourses/:title: URL pattern:title: Dynamic segment (placeholder)courses: Controller name (CoursesController)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.
Sign up for my newsletter
Let's learn to become better developers.