The Rails Router
In its essence, the routing system in Rails determines which code (specifically, an action method in a controller class) should be executed when the application 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", to: "courses#show"
This simple route consists of a few different components.
get
: HTTP verbcourses/:title
: URL patterntitle
: Dynamic segment keycourses
: Controller name (CoursesController
)show
: Action name (show
)
The above route tells the Rails router to:
- match any requests to
courses/:title
, where:title
can be any string, such ascourses/hello
,courses/ruby
, etc. - route this request to the
show
action method on theCoursesController
class. - access the title using
params[:title]
in the controller 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.
In addition, the router serves a dual purpose in Rails. In addition to routing the incoming request to a controller action, it can also dynamically generate the URLs for you, so you don't need to hard-code string URLs throughout your app. Not only this approach is more maintainable, it also reads well and makes your codebase more expressive. We'll explore the named routes in a later chapter in this book.
That's it for now. In the next lesson, we will explore and understand the routes.rb
file.
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. You can also subscribe to my blog to receive future posts via email.