N5. Post 리스트와 생성

2020. 7. 5. 16:42Rails 5 on aws c9

포스트를 쓰고, 작성된 포스트가 리스트에 뜨는 기능을 구현해보자.

materialize의 card에 가보면 다음과 같이 나온다.

 

class PostsController < ApplicationController
  def index
  end

  def new
  end
end

views/posts/new.html.erb 추가

<div class="container">
    <div class="row">
        <div class="card col s12">
            <div class="card-content">
                <div class="card-title">
                    새 글 작성하기
                </div>
                <%= form_tag posts_path do %>
                <div class="input-field">
                    <%=text_area_tag :content, nil, class: "materialize-textarea", placeholder: "무슨 생각을 하고 있나요?" %>
                </div>
                <div class="input-field">
                    <%= button_tag "작성하기", class: "btn" %>
                </div>
                <% end %>
            </div>
        </div>
    </div>
</div>

text_area_tag 헬퍼

<%=text_area_tag :content, nil, class: "materialize-textarea", placeholder: "무슨 생각을 하고 있나요?" %>

:content ⇒ 네임값은 content

, nil ⇒ 미리 들어가 있는 값은 nil

, class: "materialize-textarea" ⇒ html class에 materialize-textarea 추가

, placeholder: "무슨 생각을 하고 있나요?" ⇒ 글쓰기전에 연하게 뜨는 값

작성하기를 누르면 에러가 뜬다 (create action이 없다)

 

class PostsController < ApplicationController
  def index
  end

  def new
  end

  def create
    #new_post라는 임시변수를 만들고
    #Post 모델에서 새로운 객체를 생성해서
    #user_id: 는 현재 로그인한 사람의 id를 넣고
    #내용은 파리미터로 온 content를 넣어서 저장해주겠다.
    new_post = Post.new(user_id: current_user.id, content: params[:content])
    if new_post.save
      redirect_to root_path
    else
      redirect_to new_post_path
    end
  end
end 

views/posts/index.html.erb

<div class="container">
    <div class="row">
        <!-- 작은 사이즈에선 12개로 꽉차고, 중간사이즈부터는 4를 차지-->
        <div class="col s12 m4">
            <div class="card">
                <div class="card-image">
                    <!-- 일단은 샘플 이미지 -->
                    <img src="http://materializecss.com/images/office.jpg"/>
                </div>
                <div class="card-content">
                    <div class="card-title">
                        <!-- 로그인했다면, 현재 유저의 이름이 뜬다 -->
                        <%= current_user.name %>
                    </div>
                    <p>
                        이메일 : <%= current_user.email %>
                    </p>
                    <p>
                        <!-- posts_count 는 컨트롤러에서 작성을 해줘야 뜬다 -->
                        올린 글 개수 : <%= @posts_count %>
                    </p>
                    <!--헬퍼를 이용해 포스트 작성하기로 이동-->
                    <%= link_to new_post_path do %>
                        <button class="btn">글 쓰기</button>
                    <% end %>
                </div>
            </div>
        </div>
        <!-- 작은 사이즈에선 12개로 꽉차고, 중간사이즈부터는 8를 차지-->
        <div class="col s12 m8">
            <!-- @posts : DB에 저장된 모든 포스트를 컨트롤러에서 역순으로 보내줌-->
            <!-- 이를 하나하나 뽑아 임시변수 post로 받음-->
            <% @posts.each do |post| %>
            <div class="card">
                <div class="card-content">
                    <!-- 해당포스트의 작성자의 이름을 출력 -->
                    <span class="card-title"><%= post.user.name %></span>
                    <span><%=post.created_at %></span>
                    <p><%= post.content %></p>
                </div>
                <div class="card-action">
                    <a href="#">좋아요</a><a href="#">댓글 달기</a>
                </div>
            </div>
            <% end %>
        </div>
    </div>
</div>

controllers/post_controller.rb

class PostsController < ApplicationController
  before_action :authenticate_user!

  def index
    # views/posts/index.html.erb 에서 볼 수 있음
    # @posts변수에 모든 포스트를 created_at 기준 역순으로 정렬한걸 할당
    @posts = Post.all.order('created_at desc')
    # @posts_count 변수에 현재 로그인한 유저의 포스트 수를 할당
    @posts_count = current_user.posts.length
  end

  def new
  end

  def create
    #new_post라는 임시변수를 만들고
    #Post 모델에서 새로운 객체를 생성해서
    #user_id: 는 현재 로그인한 사람의 id를 넣고
    #내용은 파리미터로 온 content를 넣어서 저장해주겠다.
    new_post = Post.new(user_id: current_user.id, content: params[:content])
    if new_post.save
      redirect_to root_path
    else
      redirect_to new_post_path
    end
  end
end

 

'Rails 5 on aws c9' 카테고리의 다른 글

N6. Post 수정과 삭제  (0) 2020.07.05
N5-1. post 결과물을 json으로 응답받기  (0) 2020.07.05
N4. model relation  (0) 2020.07.05
N3. Devise 적용하기  (0) 2020.07.05
N2. Materialize 적용하기  (0) 2020.07.05