![](https://books.writesoftwarewell.com/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsiZGF0YSI6MzUsInB1ciI6ImJsb2JfaWQifX0=--abb3d350afbb2fc21bdbb5f6578158934d43fb04/5.png)
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.
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.