댓글 작성 기능 만들기
5-4-1 Comments 컨트롤러 생성
이번 장에서는 포스트에 댓글 다는 기능을 구현해보도록 하겠습니다.
rails g controller Comments
명령어로 Comments 컨트롤러를 생성합니다.
5-4-2 routes 설정
posts에 속한 라우팅 규칙으로 만들어 주겠습니다.
config/routes.rb 파일을 수정합니다.
resources :posts, except: [:show] do
resources :comments, only: [:create, :destroy]
end
$ rake routes
명령어로 주소 규칙을 눈으로 확인해주세요.
5-4-3 댓글 작성
댓글 작성 폼을 만들어 보겠습니다.
app/views/posts/_post.html.erb 를 수정합니다
<%= form_tag post_comments_path(post) do %>
<div class="input-field">
<%= text_area_tag :content, nil, class: "materialize-textarea", placeholder: "댓글을 작성해주세요.", required: true %>
</div>
<div class="input-field">
<%= button_tag "댓글 쓰기", class: "btn" %>
</div>
<% end %>
5-4-4 Comment 모델 생성
rails g model Comment
명령어로 Comment 모델을 생성합니다
5-4-5 comments migration 수
생성된 migrate 파일을 열어 user_id, post_id, content를 추가합니다.
...
t.integer :user_id
t.integer :post_id
t.text :content
...
5-4-6
rails db:migrate
명령어로 comments 테이블을 데이터베이스에 생성해줍니다.
5-4-7
User, Post, Comment 모델 간 관계설정을 해줍니다.
Comment 모델은 User 모델과 N:1관계를 가지면서 동시에 Post 모델과도 N:1 관계를 가지고 있습니다.
app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
app/models/user.rb
...
has_many :comments
...
app/models/post.rb
...
has_many :comments
...
5-4-8
댓글 작성 기능을 구현합니다.
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
new_comment = Comment.new(content: params[:content],
post_id: params[:post_id],
user_id: current_user.id)
new_comment.save
redirect_back(fallback_location: root_path)
end
end
5-4-9
댓글 리스트 뷰를 만들어 보겠습니다.
app/views/posts/_post.html.erb
<% if post.comments.present? %>
<ul class="collection">
<% post.comments.each do |comment| %>
<li class="collection-item">
<span class="title"><%= comment.user.name %></span>
<span class="right"><%= comment.created_at %></span>
<p><%= comment.content %></p>
<% if comment.user.id == current_user.id %>
<div><%= link_to "삭제", post_comment_path(post, comment), method: "delete" %></div>
<% end %>
</li>
<% end %>
</ul>
<% end %>
5-4-10 댓글 삭제 기능 구현
댓글 삭제 기능을 구현합니다.
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :check_ownership!, only: [:update, :destroy]
def create
new_comment = Comment.new(content: params[:content],
post_id: params[:post_id],
user_id: current_user.id)
new_comment.save
redirect_to :back
end
def destroy
@comment.destroy
redirect_to :back
end
private
def check_ownership!
@comment = Comment.find_by(id: params[:id])
redirect_to root_path if @comment.user.id != current_user.id
end
end