1.概要
本記事では、Ruby on Railsを使って実装したTweetアプリにおいて、コメント(Comment)機能に編集・削除機能を追加する方法を解説します。
コメント機能を実装してない人はこちら!
2.ルーティングを追加
config/routes.rb
resources :tweets do
resources :comments, only: [:create, :edit, :update, :destroy]
end
3.コントローラーを編集
controllers/comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :set_comment, only: [:edit, :update, :destroy]
before_action :authorize_user!, only: [:edit, :update, :destroy]
def create
tweet = Tweet.find(params[:tweet_id])
comment = tweet.comments.build(comment_params)
comment.user = current_user
if comment.save
flash[:success] = "コメントしました"
else
flash[:error] = "コメントできませんでした"
end
redirect_back(fallback_location: root_path)
end
def edit
@tweet = @comment.tweet
end
def update
if @comment.update(comment_params)
flash[:success] = "コメントを更新しました"
redirect_to tweet_path(@comment.tweet)
else
flash[:error] = "更新に失敗しました"
render :edit
end
end
def destroy
@comment.destroy
flash[:success] = "コメントを削除しました"
redirect_back(fallback_location: root_path)
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def authorize_user!
redirect_to root_path unless @comment.user == current_user
end
def comment_params
params.require(:comment).permit(:content)
end
end
###すべて書き換えで大丈夫だよ!
4.編集画面を作成
views/comments/edit.html.erb
<h2>コメントを編集</h2>
<%= form_with(model: [@tweet, @comment], local: true) do |f| %>
<%= f.text_area :content %><br>
<%= f.submit "更新する" %>
<% end %>
<%= link_to "戻る", tweet_path(@tweet) %>
5.コメント一覧に編集・削除ボタンを追加
views/tweets/show.html.erb
<% @comments.each do |c| %>
<div>
<strong><%= c.user.email %></strong><br>
<%= c.content %>
</div>
<% if c.user == current_user %>
<%= link_to "編集", edit_tweet_comment_path(@tweet, c) %>
<%= button_to "削除", tweet_comment_path(@tweet, c), method: :delete, data: { confirm: "本当に削除しますか?" } %>
<% end %>
<hr>
<% end %>
###こちらは一部だけ!