コメント機能の実装

commentモデルの作成

rails g model comment body:text user:references board:references

 

アソシエーションの追加(user.rb, board.rb)

has_many comments, dependent: :destroy

 

ルーティングの定義

resources :boards do 

 resources :comments, shallow: true

end

ルーティングをこのように定義することでどのboardに紐付いたcommentかをURLから判別できるようになる。

 

shallow: true

ネストすることによって長くなったURLを短くすることができる。

 

commentsコントローラーの作成

rails g controller comments

class CommentsController < ApplicationController
def create
comment = current_user.comments.build(comment_params)
if comment.save
flash[:success] = "コメントを作成しました"
redirec_to board_path(comment.board)
else
flash[:danger] = 'コメントを作成できませんでした'
redirec_to board_path(comment.board)
end
end

private

def comment_params
params.require(:comment).permit(:body).marge(board_id: params[:board_id])
end
end

 

boards_controller

def show
@board = Board.find(params[:id])
@comment = Comment.new
@comments = @board.comments.includes(:user).order(created_at: :desc)
end
  
viewの作成
comments/_form.html.erb
<div class="row mb-3">
<div class="col-lg-8 offset-lg-2">
<%= form_with model: comment, url: [board, comment], local: true do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :body %>
<%= f.text_area :body, class:'form-control mb-3', id: 'js-new-comment-body', row: 4 %>
<%= f.submit '作成', class:'btn btn-primary'%>
<% end %>
</div>
</div>
comments/_comments.html.erb
<div class="row">
<div class="col-lg-8 offset-lg-2">
<table id="js-table-comment" class="table">
<%= render comments %>
</table>
</div>
</div>

comments/_comment.html.erb

<%= comment.body %>

boards/show.html.erb

<%= render 'comments/form', { board: @board, comment: @comment }%>
<%= render 'comments/comments', { comments: @comments } %>