In this tutorial, we are going to explore how to create resourceful routes in Rails. Rails provides a set of routing methods, which can streamline your route definitions. By the end, you will have a clear understanding of how to create and use resourceful routes.
What you will learn:
- What resourceful routes are and why they are useful
- How to define resourceful routes
- How to use resourceful routes to connect with controllers
Prerequisites:
- Basic understanding of Ruby on Rails
- Ruby on Rails installed on your system
- Basic understanding of MVC (Model, View, Controller) architecture
resources
is a method provided by Rails. It creates routes for multiple actions (index, show, new, edit, create, update, and destroy) by default. By using resources
, you can avoid writing each route manually.
For example, consider a blog application. For posts, we usually need routes for displaying all posts, a single post, creating a new post, editing a post, deleting a post, etc. Instead of manually defining each route, you can use resources :posts
in your routes file.
Rails.application.routes.draw do
resources :posts
end
This will generate all seven default routes related to posts.
Let's look at some examples to understand better:
The following code snippet is an example of how you can define resourceful routes for posts:
Rails.application.routes.draw do
resources :posts
end
This will generate the following routes:
GET /posts
GET /posts/:id
GET /posts/new
GET /posts/:id/edit
POST /posts
PATCH/PUT /posts/:id
DELETE /posts/:id
If you want only specific routes for a resource, you can do that with the only
option:
Rails.application.routes.draw do
resources :posts, only: [:index, :show]
end
This will generate only two routes:
GET /posts
GET /posts/:id
In this tutorial, we learned about resourceful routing in Rails. We covered what resourceful routes are, how to define them, and how they can save you time and make your code cleaner.
For further learning, you can explore nested resources and how to customize resourceful routes.
Here are some additional resources:
- Rails Routing from the Outside In
- Rails Resourceful Routes
Exercise 1: Define resourceful routes for a resource named 'articles' that only has 'index' and 'show' actions.
Exercise 2: Define resourceful routes for a resource named 'comments' that has all actions except 'destroy'.
Solutions:
Exercise 1:
Rails.application.routes.draw do
resources :articles, only: [:index, :show]
end
Exercise 2:
Rails.application.routes.draw do
resources :comments, except: [:destroy]
end
For further practice, try to create a simple blog application where you can create, read, update and delete posts using resourceful routes.