コメント機能

コメント機能の要件

  • 入力フォームに入力した内容で画面が書き換わること。
  • 画面が変更されないこと。
  • 更新時にURLが変更されないこと。

モデル

(routes.rb)

Rails.application.routes.draw do
  resources :blogs do
    resources :comments
  end
end
$ rails g model Comment blog:references content:text

$ rails db:migrate

(models/blog.rb)

class Blog < ApplicationRecord
  has_many :comments, dependent: :destroy
end

(models/comment.rb)

class Comment < ApplicationRecord
  belongs_to :blog
end

コントローラ

$ rails g controller comments create

不要なroutes消しておく

(comments_controller.rb)

class CommentsController < ApplicationController
  def create
    @blog = Blog.find(params[:blog_id])
    @comment = @blog.comments.build(comment_params)
    respond_to do |format|
      if @comment.save
        format.js { render :index }
      else
        format.html { redirect_to blog_path(@blog) , notice: '投稿できませんでした' }
      end
    end
  end
  
  private

  def comment_params
    params.require(:comment).permit(:blog_id, :content)
  end
end

(blogs_controller.rb)

def show
# 2行追加
  @comments = @blog.comments
  @comment = @blog.comments.build
end

ビュー

(blogs/show/html/erb)

<div id ="comments_area">
  <%= render partial: 'comments/index', locals: { comments: @comments, blog: @blog } %>
</div>
  <%= render partial: 'comments/form', locals: { comment: @comment, blog: @blog } %>

(app/views/comments/_form.html.erb)

<%= form_with(model: [blog, comment]) do |f| %>
  <%= f.label :content%>
  <%= f.text_field :content %>
  <%= f.submit %>
<% end %>

(app/views/comments/_index.html.erb)

<ul>
  <% comments.each do |comment| %>
    <% if comment.id.present? %>
      <li>
        <p><%= comment.content %></p>
      </li>
    <% end %>
  <% end %>
</ul>

(app/views/comments/index.js.erb)

$("#comments_area").html("<%= j(render 'comments/index', { comments: @comment.blog.comments, blog: @comment.blog }) %>")
$("#comment_content").val('')