[Rails] CRUD 기능 구현(Creat / Read)[2]

728x90

Creat, Read 하기


구현 예정 기능

  • 간단한 글과 제목을 작성하고 그것을 한눈에 볼수있는 페이지

생성 페이지

  • 모든 글을 보는 페이지 index
  • 글을 작성하는 form이 있는 페이지 new
  • 하나의 글을 보는 상세 페이지 show

생성할 액션

  1. index
  2. new
  3. create(글을 작성하는 액션)
  4. show

1단계: Create , Read를 할 controller , action 생성


$ rails g controller posts index new create show
  • controller 명은 Rails 규칙에 따라서 복수형 입니다.
  • 보통 그 컨트롤러에서 다르고있는 리소스의 복수형으로 만듭니다.
  • 자동으로 routes, controller, view가 설정됩니다.

create는 글을 작성하는 액션을 위한 페이지 이므로 app/views/posts/create.html.erb는 삭제

2단계: index만들기 (routes, action, view 설정)


자동 생성된 config/routes.rb 에 방금 만든 액션을 작성해 줍니다.

Rails.application.routes.draw do
  # root 주소 추가
  root 'posts#index'
  get 'posts/index'
  get 'posts/new'
  get 'posts/create'
  get 'posts/show'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

다음으로 app/controllers/posts_controller.rb 에서 index action 부분에 아래와 같이 코드를 작성.

class PostsController < ApplicationController
  def index
        @posts = Post.all
  end

    [...]
end

3번째 줄의 @posts = Post.all 코드로 모든Post 모델의 데이터를 posts로 대입

모던 클래스의 all 메서드 → SELECT * FROM [table]을 실행시켜 모든 값들을 객채의 배열(ORM)로 리턴함

다음으로 view에서 posts를 출력합니다.

app/views/posts/index.html.erb

<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
    <tr>
        <th>id</th>
        <th>제목</th>
        <th>내용</th>
        <th>생성일</th>
        <th>수정일</th>
    </tr>
    <% @posts.each do |post| %>
        <tr>
            <td><%= post.id %></td>
            <td><%= post.title %></td>
            <td><%= post.content %></td>
            <td><%= post.created_at %></td>
            <td><%= post.updated_at %></td>
        </tr>
    <% end %>
</table>

3단계: new 만들기(route, action, view 설정)


app/views/posts/new.html.erb

<h4>
    새 글 작성
</h4>
<form action="/posts/create" method="POST">
    <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
    <input type="text" name="title">
    <br/>
    <textarea name="content"></textarea>
    <button>
        제출
    </button>
</form>

위의 authenticity_token 은 CSRF 공격을 대응하는 코드
쉽게 말해 해킹공격 방어용 코드 입니다.
Rails에서는 POST,PUT,DELETE 등 HTTP 메서드로 요청을 보낼 때, 난수화된 토큰을 생성하여 함께 전송 합니다. , 또한 토큰과 요청정보로 전달된 토큰이 일치하는 경우에만 요청을 처리 합니다.

config/routs.rb

Rails.application.routes.draw do
  get 'posts/index'
  get 'posts/new'
  post 'posts/create'
  get 'posts/show'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

get → post

데이터 저장할 때는 get보다 post가 적절

(get은 데이터 추출 할때 , ?키=밸류 와 같은 쿼리 파라미터에 정보 노출, 용량 제한 but post는 주소 보이지 않고, 용량 제한 없음)

4단계: create만들기


app/controllers/posts_controller.rb

class PostsController < ApplicationController
  [...]

  def create
      Post.create(title: params[:title], content: params[:content])
      redirect_to "/posts/index"
  end

  [...]
end

5단계: show만들기


<a href="/posts/new">새 글 작성</a>
<hr/>
<table border="1">
    <tr>
        <th>id</th>
        <th>제목</th>
        <th>내용</th>
        <th>생성일</th>
        <th>수정일</th>
        <!-- 추가 -->
        <th>링크</th>
        <!-- 추가 끝 -->
    </tr>
    <% @posts.each do |post| %>
        <tr>
            <td><%= post.id %></td>
            <td><%= post.title %></td>
            <td><%= post.content %></td>
            <td><%= post.created_at %></td>
            <td><%= post.updated_at %></td>
            <!-- 추가 -->
            <td><a href="/posts/show/<%= post.id %>">보기</a></td>
            <!-- 추가 끝 -->
        </tr>
    <% end %>
</table>

/posts/show/<%= post.id %> 상세페이지는 특정 데이터의 상세 정보를 알아야 합니다.

따라서 라우트 파라미터 방식 으로 특정 데이터의 id를 보냅니다.

config/routes.rb

Rails.application.routes.draw do
  get 'posts/index'
  get 'posts/new'
  post 'posts/create'
    # 추가
  get 'posts/show/:id' => "posts#show"
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

show 뒤의문자는 id에 대입된 뒤, 컨트롤러에 전달 됩니다.

:변수명

posts/:post_id/comments/:comment_id 방식처럼 라우트 파라미터 변수를 여러개 추가 하는 것도 가능 합니다.

app/controllers/posts_controller.rb

class PostsController < ApplicationController
    [...]

  def show
      @post = Post.find(params[:id])
  end
end

id 값을 params[:id] 로 추출 합니다.

그 결과를 post 에 저장합니다.

find(val) 은 SQL 에서 SELECT * FROM table WHERE id=val; 을 실행합니다.

app/view/posts/show.html.erb

<p>
    title : <%= @post.title %>
</p>

<p>
    content : <%= @post.content %>
</p>

<a href="/posts/index">Back</a>

728x90

댓글

Designed by JB FACTORY