LoginSignup
0
1

More than 1 year has passed since last update.

rails コメント機能実装

Posted at

①コメントを記録するモデルを作成しよう

rails g model post_comment comment:text user_id:integer book_id:integer

②マイグレートしてテーブルをデータベースに登録する。

rails db:migrate

③アソシエーションで関連付けを行う

PostComment.rb
class PostComment < ApplicationRecord
  belongs_to :user
  belongs_to :book
end
user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable


  has_many :active_relationships, class_name: 'Follow', foreign_key: 'user_id'
  has_many :passive_relationships, class_name: 'Follow', foreign_key: 'target_user_id'
  has_many :followings, through: :active_relationships, source: :target_user
  has_many :followers, through: :passive_relationships, source: :user




  has_many :books, dependent: :destroy

  # コメントの追加、記事の削除と同時に削除する
  has_many :post_comments, dependent: :destroy
  attachment :profile_image, destroy: false

  validates :name, length: {maximum: 20, minimum: 2}, uniqueness: true
  validates :introduction, length: {maximum: 50}

  # いいねしたかの判定

  def already_favorited?(book)
    self.favorites.exists?(book_id: book.id)
  end

end

class Book < ApplicationRecord
    belongs_to :user
    # 多くの良いねを受け取る可能性がある、記事の削除と同時に削除する(いいね)
    has_many :favorites, dependent: :destroy
    # コメントの追加、記事の削除と同時に削除する
    has_many :post_comments, dependent: :destroy


    validates :title, presence: true
    validates :body, presence: true, length: {maximum: 200}
end

④コントローラーを作成しアクションを書く

PostCommentsController.rb
class PostCommentsController < ApplicationController
  def create
    #本に対してのコメントのためどの本にコメントを書くか決めるためfindする
    book = Book.find(params[:book_id])
  #現在のユーザーが新しい投稿をする(post_comment_paramsでコメントを許可されている)
    comment = current_user.post_comments.new(post_comment_params)
  #本のidとコメントのidは一緒
    comment.book_id = book.id
  #コメントを保存する
    comment.save
   #投稿後詳細画面へ遷移する
    redirect_to book_path(book)
  end

  def destroy
  #コメントidとコメントの記述idを削除する
    PostComment.find_by(id: params[:id], book_id: params[:book_id]).destroy
    redirect_to book_path(params[:book_id])
  end

  private
  def post_comment_params
    params.require(:post_comment).permit(:comment)
  end 
end

⑤ネストする

routes.rb
Rails.application.routes.draw do
  devise_for :users

  root 'homes#top'
  get 'home/about' => 'homes#about'


  resources :books do
   resources :post_comments, only: [:create, :destroy]
  end

end

⑥viewに書く

index.html.erb
<%= link_to "#{ book.post_comments.count} コメント", book_path(book.id) %></td>

・コメント数がわかる 「0 コメント」という感じになる
・リンク先は、ブックのshowへ行く

show.html.erb
            <td><div class="comments">
              #@bookでidを取ってきてくれて、どの投稿にコメントが何個になっているかを表示してくれる。本のコメントの数を表示と覚えよう。
              <p>コメント件数:<%= @book.post_comments.count %></p>
              <% @book.post_comments.each do |post_comment| %>
                <p><%= image_tag('no_image.jpg') %></p>
                <%= post_comment.user.name %>
                <%= post_comment.created_at.strftime('%Y/%m/%d') %><%= post_comment.comment %>
                  <% if post_comment.user == current_user %>
                  <div class="comment-delete">
#遷移してpost_commentのデストロイアクションを実行して、コメントのbook=idとコメントのレコードを削除する
                  <%= link_to "削除", book_post_comment_path(post_comment.book, post_comment), method: :delete %>
                </div>
                <% end %>
            <% end %>
            </div>
          </td>
        </tr>
      </table>
            <div class="">
            <%= form_with model:[@book,@post_comment], local: true do |f| %>
              <%= f.text_area :comment, size:"90x5" %>
              <%= f.submit "送信する" %>
            <% end %>
            </div>
0
1
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
1