🐥

【Ruby on Rails】コメント機能

2022/04/20に公開

環境

Windows10
cloud9
Ruby2.6.3
Rails6.1.4

本題

※User機能と投稿機能(bookモデル)は作成済みで記述してあります。
1.コメント機能のモデルを作成

$ rails g model comment

2.マイグレーションファイルの中身を編集

class CreateLikes < ActiveRecord::Migration[6.1]
  def change
    create_table :likes do |t|
      t.integer :user_id ←ここ追加
      t.integer :book_id ←ここ追加
      t.text :comment ←ここ追加
      t.timestamps
    end
  end
end

※integer: 文字列型
3.アソシエーションを設定
※アソシエーションとは?
 モデル同士の繋がりを示すこと。
今回では、ユーザーが投稿に対してコメント送信することが出来るようにコメント機能を作成中です。
アソシエーションを設定する事で、ユーザーとコメント同士が繋がり、誰がコメントしたかが分かります。

comment.rb

¦
belongs_to :user
belongs_to :book
¦

コメントとユーザーを繋げます
user.rb

¦
has_many :comments, dependent: :destroy
¦

コメントと投稿(book)を繋げます
book.rb

¦
has_many :comments, dependent: :destroy
¦

4.ルーティングを作成

¦
resources :books, only: [:new, :create, :index, :show, :edit, :update, :destroy] do
    resources :comments, [:create, :destroy]
end
¦

5.コメント機能のコントローラーを作成

$ rails g controller comments
class LikesController < ApplicationController

  def create
    book = Book.find(params[:book_id])
    comment = current_user.comments.new(comment_params)
    comment.book_id = book.id
    comment.save
    redirect_to book_path(book)
  end

  def destroy
    Comment.find(params[:id]).destroy
    redirect_to book_path(params[:book_id])
  end
end

6.コメント機能のviewを作成
_comment.html.erb

<table>
  <tbody>
    <% book.comments.each do |comment| %>
    <tr>
      <td><%= image_tag comment.user.get_profile_image,size: "20x20" %></td>
      <td><%= comment.user.name %></td>
      <td><%= comment.comment %></td>
      <td>
        <% if comment.user == current_user %>
        <%= link_to "削除", book_comment_path(comment.book,comment), method: :delete, class: "btn btn-sm btn-danger p-0 p-1", style: "font-size: 8px;" %>
        <% end %>
      </td>
    </tr>
    <% end %>
  </tbody>
</table>

_comment_form.html.erb

<%= form_with model:[book,comment] do |f| %>
<%= f.text_area :comment, placeholder: "コメントをここに" %>
<%= f.submit "送信" %>
<% end %>

お疲れ様でした。
何か間違いがありましたら、ご指摘宜しくお願い致します。

Discussion