๐Ÿ—บ๏ธ

RESTful Routes

One line of resources generates 7 routes automatically

Rails routing fully supports REST principles. A single resources :posts line auto-generates 7 routes needed for CRUD.

Generated 7 routes:

GET    /posts          โ†’ posts#index    (list)
GET    /posts/:id      โ†’ posts#show     (detail)
GET    /posts/new      โ†’ posts#new      (create form)
POST   /posts          โ†’ posts#create   (create action)
GET    /posts/:id/edit โ†’ posts#edit     (edit form)
PATCH  /posts/:id      โ†’ posts#update   (update action)
DELETE /posts/:id      โ†’ posts#destroy  (delete action)

Nested resources: resources :posts do; resources :comments; end for /posts/1/comments
Namespaces: namespace :admin do; resources :posts; end for /admin/posts
Custom routes: Define additional routes with member and collection

Use the rails routes command to view all defined routes.

Architecture Diagram

7 routes generated by a single line of <code>resources :posts</code>:
GET /posts posts#index List
GET /posts/:id posts#show Detail
GET /posts/new posts#new New form
POST /posts posts#create Create
GET /posts/:id/edit posts#edit Edit form
PATCH /posts/:id posts#update Update
DELETE /posts/:id posts#destroy Delete
URL Helpers are also auto-generated:
posts_path post_path(@post) new_post_path edit_post_path(@post)
Key point: Generate meaningful RESTful APIs with a single line using <strong>HTTP Method + URL combinations</strong>

Key Points

1

Define resources :posts in config/routes.rb

2

Check generated routes with rails routes (prefix, verb, URI, controller#action)

3

Controller#Action determined by HTTP Method + Path

4

Select needed routes with only:/except: options

5

Add custom routes with member/collection blocks

6

Manage URL and controller namespaces with namespace/scope

Pros

  • Intuitive and predictable URL design
  • 7 routes with one line โ†’ productivity
  • Meaningful URLs using HTTP Methods
  • URL Helpers auto-generated (posts_path, post_path, etc.)

Cons

  • Non-REST actions need separate definition
  • Excessive nesting leads to long URLs
  • Non-resource pages (about, contact) need direct get definition
  • Need to separate API vs HTML routes

Use Cases

CRUD implementation REST API server Admin panel (namespace :admin) Nested resources (posts โ†’ comments)