In this tutorial, we aim to equip you with the best practices for managing routes in your Rails applications. By the end of this guide, you should be able to organize and manage your routes effectively, which will bring about maintainability and scalability in your applications.
You will learn:
Prerequisites:
Rails routing is a core concept in Rails applications. It is the process of mapping URLs to controller actions. It tells Rails what it should do when a specific URL is hit.
Here are some best practices to follow for route management:
1. Restrict Auto-generated Routes:
When you declare a resource in the routes file, Rails creates seven different routes for you automatically. If you don't need all the routes, you can restrict them using the :only
or :except
option.
# config/routes.rb
resources :photos, only: [:index, :show]
This will only generate index
and show
routes for photos.
2. Use Nested Routes Wisely:
While nested routes can be very useful, they can also lead to unnecessary complexity. As a rule of thumb, don't go beyond one level of nesting.
# config/routes.rb
resources :publishers do
resources :books
end
3. Use Member and Collection Routes:
Member routes act on a member of the resource while collection routes act on a collection of resources.
# config/routes.rb
resources :photos do
get 'preview', on: :member
get 'search', on: :collection
end
Example 1: Basic Route:
# config/routes.rb
get '/about', to: 'pages#about'
This tells Rails to direct requests for '/about' to the about
action of the pages
controller.
Example 2: Using namespaces:
# config/routes.rb
namespace :admin do
resources :orders
end
This will generate a bunch of routes that start with '/admin/orders' and route to the Orders
controller inside the Admin
module.
In this tutorial, we have covered how to effectively manage routes in Rails. We've discussed how to restrict auto-generated routes, how to use nested routes, and the use of member and collection routes.
For further learning, consider delving deeper into Rails routing by exploring shallow nesting, direct and resolved routes.
Exercise 1: Create a route that maps to a 'welcome' action of a 'pages' controller when '/welcome' is hit.
Solution:
# config/routes.rb
get '/welcome', to: 'pages#welcome'
Exercise 2: Create a resource for articles and restrict it to only 'index' and 'show' actions.
Solution:
# config/routes.rb
resources :articles, only: [:index, :show]
Exercise 3: Create a nested resource for comments inside articles and a collection route 'search' for articles.
Solution:
# config/routes.rb
resources :articles do
resources :comments, only: [:index, :create, :destroy]
get 'search', on: :collection
end
These exercises should help you practice the concepts you've learned. Continue to experiment with different options and settings for Rails routing.