Creating Resourceful Routes

Tutorial 2 of 5

Creating Resourceful Routes

1. Introduction

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

2. Step-by-Step Guide

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.

Example:

Rails.application.routes.draw do
  resources :posts
end

This will generate all seven default routes related to posts.

3. Code Examples

Let's look at some examples to understand better:

Example 1:

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

Example 2:

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

4. Summary

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

5. Practice Exercises

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.