0
0
Ruby on Railsframework~5 mins

RESTful resource routes in Ruby on Rails

Choose your learning style9 modes available
Introduction

RESTful resource routes help organize web app URLs to match common actions like viewing, creating, or deleting data. This makes your app easier to understand and use.

When building a web app that manages items like posts, users, or products.
When you want to follow a standard way to handle URLs and actions in your app.
When you want Rails to automatically create routes for common actions.
When you want to keep your code clean and avoid writing many individual routes.
Syntax
Ruby on Rails
resources :items

This single line creates many routes for standard actions like index, show, new, create, edit, update, and destroy.

You replace items with the name of your resource, usually plural.

Examples
Creates all RESTful routes for books, like /books, /books/:id, /books/new, etc.
Ruby on Rails
resources :books
Creates only the index and show routes for users, limiting available actions.
Ruby on Rails
resources :users, only: [:index, :show]
Creates all routes for comments except the destroy route.
Ruby on Rails
resources :comments, except: [:destroy]
Sample Program

This code sets up all standard RESTful routes for articles in a Rails app.

It creates routes like:

  • GET /articles (index)
  • GET /articles/:id (show)
  • GET /articles/new (new)
  • POST /articles (create)
  • GET /articles/:id/edit (edit)
  • PATCH/PUT /articles/:id (update)
  • DELETE /articles/:id (destroy)
Ruby on Rails
Rails.application.routes.draw do
  resources :articles
end
OutputSuccess
Important Notes

Use rails routes command in terminal to see all routes created by resources.

You can customize routes by adding only or except options to limit actions.

RESTful routes help keep your app organized and follow web standards.

Summary

RESTful resource routes create standard URLs for common actions automatically.

Use resources :name to generate all routes for a resource.

Customize routes with only or except to control available actions.