Getting Started with Rails
위 튜토리얼을 따라 학습하며 작성한 글입니다.
A Request’s Journey Through Rails
To get Rails saying “Hello”, you need to create at minimum a route, a controller with an action, and a view. A route maps a request to a controller action. A controller action performs the necessary work to handle the request, and prepares any data for the view. A view displays data in a desired format.
Rails 가 Hello 라고 말하려면 최소한 route, controller with action, view 가 갖춰져야한다.
controller 는 request 에 필요한 작업을 수행하고 view 에 대한 data 를 준비한다.
view 는 원하는 포멧으로 data 를 출력한다.
In terms of implementation: Routes are rules written in a Ruby DSL (Domain-Specific Language). Controllers are Ruby classes, and their public methods are actions. And views are templates, usually written in a mixture of HTML and Ruby.
구현 측면에서:
Route 는 Ruby DSL 로 작성된 규칙들이다.
controller 들은 Ruby 클래스들로 이루어졌고 Ruby 의 public 메서드가 action들이다.
view 들은 보통 HTML 과 Ruby 의 혼합된 형태이다.
JSP 를 생각하면 이해가 쉽다. JSP(Java + HTML) 이 아니라 Ruby + HTML 을 사용한다고 보면 된다.
Route
route 는 HTTP 요청을 적절한 controller 와 action 으로 전달하는 역할을 한다.
예를 들어 http://example.org/products 라는 요청이 있을 때 어떤 controller 혹은 action 으로 전달할지 미리 작성해놓것이다.
URL 구성 요소
http://example.org/products?sale=true&sort=asc
- http : protocol
- example.org : host
- products : path
- ?sale=true&sort=asc : query parameter
이미 다들 잘 알 것이라 생각하고 URL 구성 요소에 대한 설명은 생략한다.
Route 작성
1
2
3
4
5
# config/routes.rb
Rails.application.routes.draw do
get "/products", to: "products#index"
end
위 코드는 GET http://주소/products 요청을 products 컨트롤러의 index 액션(메서드)로 라우팅 하는 코드이다.
config/routes.rb 에 한 줄 추가해주면 된다.
1
2
3
4
5
6
7
# config/routes.rb
Rails.application.routes.draw do
get "/products/:id", to: "products#show"
get "/blog/:title", to: "blog#show"
end
만약 /products/1 , /products/2 과 같이 패턴이 존재하는 요청이라면 /products/:id 라고 작성하면 된다.
숫자만 되는게 아니라 문자도 가능하다. /blog/hello, /blog/test 와 같은 패턴을 요청으로 받으려면 /blog/:title 이라고 작성하면 된다.
CRUD Route
CRUD 는 Route 에서 8 가지의 action 으로 작성된다.
(단순히 컨벤션인지 무조건 지켜야 하는 규칙인지 모르겠다. 따로 설명이 없다.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
get "/products", to: "products#index"
get "/products/new", to: "products#new"
post "/products", to: "products#create"
get "/products/:id", to: "products#show"
get "/products/:id/edit", to: "products#edit"
patch "/products/:id", to: "products#update"
put "/products/:id", to: "products#update"
delete "/products/:id", to: "products#destroy"
# 또는
resources :products
index
모든 record 를 보여준다.new
새 record 를 생성하는 form 을 보여준다.create
form 을 처리하여 record 를 생성한다.
맥락상 new 요청을 하면 form 을 응답받고, form 을 제출하면 create 를 호출하도록 로직을 구성해야하는것 같다.
show
특정 record 를 조회한다.edit
특정 record 를 update 하는 form 을 보여준다.update(전체)
edit form 을 처리하며 전체 record 를 업데이트한다. 일반적으로 put 요청으로 트리거된다.update(부분)
edit form 을 처리하며 record 의 일부 속성을 업데이트한다. 일반적으로 patch 요청으로 트리거된다.destroy
특정 record 를 삭제한다.
참고로 위 8가지 action 을 대체하는 shorcut 이 있다.
resources :products 를 입력하면 된다.
일부 action 만 지정하는 shorcut은 따로 있다. routing guide 참고
Route Command
1
$ bin/rails routes
터미널에서 위 명령어를 입력하면 모든 라우팅 경로를 볼 수 있다.