0
0
RailsHow-ToBeginner · 3 min read

How to Use Resources in Routes in Ruby on Rails

In Ruby on Rails, use the resources method in the config/routes.rb file to automatically generate RESTful routes for a controller. This creates standard routes for actions like index, show, new, edit, create, update, and destroy with a simple line of code.
📐

Syntax

The resources method defines RESTful routes for a resource. It automatically creates routes for common actions like listing, showing, creating, updating, and deleting items.

Basic syntax:

  • resources :resource_name - creates all 7 standard RESTful routes.
  • resources :resource_name, only: [:index, :show] - creates only specified routes.
  • resources :resource_name, except: [:destroy] - creates all except specified routes.
ruby
Rails.application.routes.draw do
  resources :articles
end
💻

Example

This example shows how to define routes for an articles resource. It creates routes for all standard RESTful actions.

Running rails routes will list all generated routes.

ruby
Rails.application.routes.draw do
  resources :articles
end
Output
Prefix Verb URI Pattern Controller#Action articles GET /articles(.:format) articles#index POST /articles(.:format) articles#create new_article GET /articles/new(.:format) articles#new edit_article GET /articles/:id/edit(.:format) articles#edit article GET /articles/:id(.:format) articles#show PATCH /articles/:id(.:format) articles#update PUT /articles/:id(.:format) articles#update DELETE /articles/:id(.:format) articles#destroy
⚠️

Common Pitfalls

Common mistakes when using resources include:

  • Forgetting to restrict routes with only or except, which can expose unwanted actions.
  • Using resource (singular) instead of resources (plural) when multiple items are needed.
  • Not nesting resources properly when dealing with related models.
ruby
Rails.application.routes.draw do
  # Wrong: exposes all routes unintentionally
  resources :users

  # Right: restrict to only index and show
  resources :users, only: [:index, :show]
end
📊

Quick Reference

Summary of resources options:

OptionDescription
resources :nameCreates all 7 RESTful routes for the resource
only: [:actions]Creates only specified routes (e.g., :index, :show)
except: [:actions]Creates all except specified routes
nested resourcesDefine resources inside another resource for related models
resource (singular)Creates routes for a singleton resource without index

Key Takeaways

Use resources :name in routes.rb to create standard RESTful routes automatically.
Restrict routes with only or except to expose only needed actions.
Use plural resources for collections and singular resource for single items.
Nest resources inside others to represent model relationships in URLs.
Check generated routes with rails routes to verify your routing setup.