0
0

More than 3 years have passed since last update.

【Rails】掲示板コメント機能実装(メモ)

Posted at

 目標

 コメント機能の実装

Image from Gyazo

 環境

  • Rails: 6.1.3
  • ruby: 3.0.0
  • mac: os

 前提

  • 掲示板投稿機能実装済み
  • 投稿テーブル名post

 実装

 1.モデルを作成

ターミナル
$ rails g model Comment comment:string post:references

生成されたマイグレーションファイル。
今思えばモデル名もコメント名もcommentで紛らわしくしちゃった気がします。。

class CreateComments < ActiveRecord::Migration[6.1]
  def change
    create_table :comments do |t|
      t.string :comment
      t.references :post, null: false, foreign_key: true

      t.timestamps
    end
  end
end

マイグレーション実行。

ターミナル
$ rails db:migrate

 2.モデルの関連付け

app/models/post.rb
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy

postは複数のコメントを持てるのでhas_many :comments
post投稿を削除した際追従して、コメントも消えてほしいのでdependent: :destroyを追記。

app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :post

1件のコメントは1件の投稿に属していますね。
このアソシエーション部分かなり重要です。

 3.ルーティング追加

config/routes.rb
Rails.application.routes.draw do
  resources :posts do
    resources :comments
  end
end

ネストしたルーティングを記述。
rails routesで確認したらpost_commnts POST/posts/:post_id/commnts(.:format)になっています。

4.コントローラー作成

ターミナル
$ rails g controller Comments

生成されたapp/controller/comments.rbcreateアクションを記述。

app/controller/comments.rb
class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comment_params)
    if @comment.save
      flash[:success] = 'コメントを投稿しました'
      redirect_to post_path(@post)
    else
      flash[:danger] = 'コメント投稿に失敗しました'
      redirect_back(fallback_location: posts_path)
    end
  end
end

private

def comment_params
  params.require(:comment).permit(:comment)
end

5.ビューに記述

投稿詳細ページにコメント投稿フォームとコメント一覧を作成する。

app/views/posts/show.html.erb
<%= form_with(model:[ @post, @post.comments.build ], local:true) do |form| %>

    <div class="form-group">
        <p>
            <%= form.label 'コメント(255文字未満)' %>
            <%= form.text_area :comment,class: 'form-control' %>
        </p>
    </div>
    <div class="form_action row">
        <%= form.submit 'コメント投稿',class: 'btn btn-primary' %>
    </div>
<% end %>

コメントしたユーザーの名前と作成時間、コメント内容の記述。

app/views/posts/show.html.erb

<% @post.comments.each do |comment| %>
   <P><%= comment.user.name %> : <%= comment.created.at %></p>

   <p><%= commet.comment %></p>
<% end %>

ざっくりとはしていますが、これで投稿に対してのコメント機能が使えるはずです、この辺りはしっかりおさえておきたいので備忘録として残しておきます。

 参考

参考にさせていただいた記事です。
https://qiita.com/nojinoji/items/2034764897c6e91ef982
https://qiita.com/__kotaro_/items/8a6bda99dab61d2a72a5

0
0
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
0
0