Rails【初心者向け】コメント機能の実装


railsでコメント機能の実装についてまとめました。

前提

Ruby on Rails での開発環境が整っている。
Posts(投稿テーブル)とUser(ユーザーテーブル)は既に作成してある。
Userテーブルはgem deviseを使っている。
今回は投稿に対してコメントを実装します。

コメント機能の実装

1.Commentモデルの作成

作成するCommentsテーブルの詳細とリレーションに関して以下の通りです。

ターミナルでモデル作成

$ rails g model comment

マイグレーションファイルの記述

20********_create_comments.rb
class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t |
      #ここから記述
      t.references :user,foreign_key: true
      t.references :post, foreign_key: true
      t.text :text,nul: false
      #ここまで記述
      t.timestamps
    end
  end
end

マイグレーションファイルの適応

$ rails db:migrate

CommentモデルとUserモデル、Postモデルを紐付ける

app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post
end
app/models/user.rb
class User < ApplicationRecord
  has_many :posts
  has_many :comments
end
app/models/post.rb
class Comment < ApplicationRecord
  has_many :users
  has_many :comments
end

2.ルーティングの作成

routes.rb
Rails.application.routes.draw do
  resources :users
  resources :posts do
    resource :comments
  end
end

3.Commentsコントローラーの作成

comments_controller.rb
class CommentsController < ApplicationController
  def create
    @comment = Comment.create(comment_params)
    redirect_back(fallback_location: root_path)
  end

 private

  def comment_params
    params.require(:comment).permit(:text).merge(user_id: current_user.id, post_id: params[:post_id])
  end
end
posts_controller.rb
class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to user_url(current_user)
    else
      render :new
    end
  end

  def show
    #Commentインスタンスの生成を書く
    #今回はPosts#showにてコメント機能を実装したいと思います。
    @comment = Comment.new
    @comments = @post.comment_cs.includes(:user)
  end

private

  def post_params
    params.require(:post).permit(:text).merge(user_id: current_user.id)
  end

  def set_post
    @post = Post.find(params[:id])
  end

end

4.ビューの作成

投稿詳細ページにコメント機能の記述を書く。

views/posts/show.html.erb

#省略

 <%= form_with model: [@post,@comment],merhod: :post,locals: true do | form | %>
    <%= form.text_area :text %>
    <%= form.submit "投稿する" %>
 <% end %>

#省略

コメント機能完成!

まとめ

今回はRailsでコメント機能をテーブル作成から行ってきました。
自分もプログラミング初心者ですのでなにか間違いがありましたらお教えください。
最後まで読んでいただきありがとうございました!