🗺️

RESTful Routes

resources 한 줄로 7개 라우트 자동 생성

Rails의 라우팅은 REST 원칙을 완벽하게 지원합니다. resources :posts 한 줄로 CRUD에 필요한 7개 라우트가 자동 생성됩니다.

생성되는 7개 라우트:

GET    /posts          → posts#index    (목록)
GET    /posts/:id      → posts#show     (상세)
GET    /posts/new      → posts#new      (생성 폼)
POST   /posts          → posts#create   (생성 처리)
GET    /posts/:id/edit → posts#edit     (수정 폼)
PATCH  /posts/:id      → posts#update   (수정 처리)
DELETE /posts/:id      → posts#destroy  (삭제 처리)

네스티드 리소스: resources :posts do; resources :comments; end/posts/1/comments
네임스페이스: namespace :admin do; resources :posts; end/admin/posts
커스텀 라우트: membercollection으로 추가 라우트 정의

rails routes 명령어로 정의된 모든 라우트를 확인할 수 있습니다.

구조 다이어그램

<code>resources :posts</code> 한 줄로 생성되는 7개 라우트:
GET /posts posts#index 목록
GET /posts/:id posts#show 상세
GET /posts/new posts#new 생성 폼
POST /posts posts#create 생성 처리
GET /posts/:id/edit posts#edit 수정 폼
PATCH /posts/:id posts#update 수정 처리
DELETE /posts/:id posts#destroy 삭제 처리
URL Helper도 자동 생성:
posts_path post_path(@post) new_post_path edit_post_path(@post)
핵심: <strong>HTTP Method + URL 조합</strong>으로 의미있는 RESTful API를 한 줄로 생성

핵심 포인트

1

config/routes.rb에 resources :posts 정의

2

rails routes로 생성된 라우트 확인 (prefix, verb, URI, controller#action)

3

HTTP 요청의 Method + Path 조합으로 Controller#Action 결정

4

only: / except: 옵션으로 필요한 라우트만 선택

5

member / collection 블록으로 커스텀 라우트 추가

6

namespace / scope로 URL 및 컨트롤러 네임스페이스 관리

장점

  • URL 설계가 직관적이고 예측 가능
  • 한 줄로 7개 라우트 생성 → 생산성
  • HTTP Method를 활용한 의미있는 URL
  • URL Helper 자동 생성 (posts_path, post_path 등)

단점

  • REST에 맞지 않는 액션은 별도 정의 필요
  • 과도한 네스팅은 URL이 길어짐
  • 리소스가 아닌 페이지(about, contact)는 get으로 직접 정의
  • API vs HTML 라우트 분리 필요

사용 사례

CRUD 기능 구현 REST API 서버 관리자 패널 (namespace :admin) 중첩 리소스 (게시글 → 댓글)