프로그래밍/Ruby & Rails
[Ruby on Rails] Post모델에 댓글(comments) 기능 추가하기
hyeoke
2018. 8. 10. 03:13
# Post 모델에 댓글 기능 추가하기
이번 포스팅에서는 게시판 글쓰기 기능에 사용자들이 댓글을 달 수 있는 Comments 모델을 추가해 보겠습니다.
# Comments 모델 생성
- 터미널
-> $rails g model comment body:text post:references
-> $rails db:migrate
# post 모델이 has_many 추가
# post.rb
has_many: comments
# user모델과 comment 모델 설정하기
- comment.rb
# comment.rb
belongs_to :user
- user.rb
# user.rb
has_many :comments
has_many :posts
- 터미널
-> $rails g migration add_user_id_to_comment user_id:integer:index
-> $rails db:migrate
# routes.rb에 코드 추가
# routes.rb
resources :posts do
resources :comments
end
# 컨트롤러 생성
- 터미널
-> $rails g controller Comments
# comment 컨트롤러에 create, destroy 액션 추가
# comments_controller.rb
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:body))
@comment.user = current_user #이 comments의 user_id를 저장하여, 댓글을 단 사용자의 이메일을 노출할 수 있음!
@comment.save
redirect_to pin_path(@pin)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
# views 파일 코드 추가
* _comment.html.erb 와 _form.html.erb 파일 생성
- views/comments/_comment.html.erb
# _comments.html.erb
<div class="">
<p class=""><strong><%= comment.user.email %></strong></p>
<p class=""><%= comment.body %></p>
<p class=""><%= time_ago_in_words(comment.created_at) %> Ago</p>
<p>
<%= link_to 'Delete', [comment.post, comment],
method: :delete,
class: "btn btn-primary",
data: { confirm: 'Are you sure?' }
%>
</p>
<hr>
<div>
- views/comments/_form.html.erb
# _form.html.erb
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :body %>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
- views/posts/show.html/erb
# show.html.erb
<div class="">
<h2><%= @post.comments.count %> Comments</h2>
<%= render @post.comments %>
<h3>Add a Comment: </h3>
<%= render "comments/form" %>
</div>