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
/posts
→
posts#index
List
/posts/:id
→
posts#show
Detail
/posts/new
→
posts#new
New form
/posts
→
posts#create
Create
/posts/:id/edit
→
posts#edit
Edit form
/posts/:id
→
posts#update
Update
/posts/:id
→
posts#destroy
Delete
posts_path
post_path(@post)
new_post_path
edit_post_path(@post)
Key Points
Define resources :posts in config/routes.rb
Check generated routes with rails routes (prefix, verb, URI, controller#action)
Controller#Action determined by HTTP Method + Path
Select needed routes with only:/except: options
Add custom routes with member/collection blocks
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