LoginSignup
5
6

More than 3 years have passed since last update.

railsでコメント機能を作ろう

Last updated at Posted at 2019-05-29

コメント機能の実装

投稿データ => Image model
コメント => Comment model

投稿フォームは投稿一覧に作成する(images#show)

Model作成

$ rails g model Comment content:string image:references
  • content => コメント格納用
  • image => imageモデルと関連付けるため

(models/comment.rb)

belongs_to :image
validates :content, presence: true
  • belongs_to => imageモデルに属している(自動記入)
  • precense: true => 空白を不可とする

(models/image.rb)

has_many :comments, dependent: :destoroy
  • has_many => たくさんのコメントを持つことができる(1対多)
  • dependent: :destroy => imageが削除されたらcommentsも削除される

Routes設定

resources :images do 
  resouces :comments, only: [:create, :destroy]
end 

生成されるURL
create =>/images/:image_id/comments
destroy =>/images/:image_id/comment/:id

  • image_idをControllerで活用
  • どの投稿の、どのコメントかを判別する必要がるためこのようになる

Controller作成

$ rails g controller comments create destroy
  • createdestroyの機能を指定する(Viewは削除)

private
  def content_params
    params.require(:comment).permit(:content)
  end 
  • ストロングパラメーターを設定する
def create
  image = Image.find(params[:image_id])
  @comment = image.comments.build(comment_params)
  if @comment.save
    flash[:success] = "コメントしました"
    redirect_back(fallback_location: image_url(image.id))
  else
    flash[:danger] = "コメントできません"
    redirect_back(fallback_location: image_url(image.id))
  end 
end 
  • params[:image_id] => URLから取得する(ルーティングで設定)
  • redirect_back(fallback_location: image_url(image.id)) => 直前のURLにリダイレクト(showで投稿しshowに戻る)

def destroy
  image = Image.find(params[:image_id])
  @comment = image.comments.find(params[:id])
  @comment.destroy
  redirect_back(fallback_location: image_path(image)
end 
  • image.comments.find(params[:id]) => 取得したimageのコメントを:idで探す

View作成

投稿フォーム

<%= form_with(model: [@image, @comment], local: true) do |f| %>
  <%= f.text_field :content %>
  <%= f.submit "コメントする", class: "btn btn-primary" %>
<% end %>
  • model: [@image, @comment] => commentimageに紐づいているモデルのため、配列にして記載する必要がある
#ImageControllerで定義
def show
  @image = Image.find(params[:id])
  @comment = @image.comments.build
end

削除ボタン

<% link_to "DELETE", image_comment_path(image_id: @image, id: comment.id), method: :delete %>
  • image_comment_path => 必要な引数を記載 (/images/:image_id/comment/:id)
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6