Everything about Rails Router
In-Depth lookout over Rails Router
Rails Router is a directing module that recognizes browser URLs and dispatches them to the controller actions requested. Basically, when a valid URL is entered on a browser, it will look for the exact controller and action associated with it.
Let’s take an example with a PostsController in which the home method is defined. So basically, the URL will end something like ‘/posts/home
’ for which a router needs to get defined. Does this lead to our next concern as to where to define it? So the routes are defined in ‘config/routes.rb
’ in the Rails project directory. Let’s get back to the example so the requirement is to have the URL as ‘/posts/home
’, so let’s define it in the routes file as,
config/routes.rbRails.application.routes.draw do
resources :posts
get ‘posts/home’, to: ‘posts#home’
end
So now on the terminal, the routes information can be extracted as,
terminal=>$ rake routesPrefix Verb URI Pattern Controller#Actionposts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
posts_home GET /posts/home(.:format) posts#home
The router automatically maps the request from the browser to the home action/method of the posts_controller.rb
. The action then determines which page it should render to the user. In our case is the home.html.erb
.
Rails Routes is a huge topic to cover in a single section as there are tons of subsections to it. Just to make it simpler, let’s divide it into pieces as below,
- Basic Routing with RESTful Design for Rails
- Customizing Rails Routes
- Constraints in Rails Routes
- Namespace vs Scope in Rails Routes
- Member vs Collection in Rails Routes
- DRY Rails Routes
With that separation done, let’s begin exploring each topic separately!