これまでに作った機能について簡単にまとめていく。
今回は、
コメント機能の作成
前提条件
何かのモデルのcrud機能があること
ログイン機能があること
ログイン機能についてはこちら
使用モデル
Userモデル
| カラム | データ型 | |
|---|---|---|
| 1 | name | string |
| 2 | text | |
| 3 | password_digest | string |
Blogモデル
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
| 3 | likes_count | integer |
Commentモデル
| カラム | データ型 | |
|---|---|---|
| 1 | content | string |
| 2 | user_id | bigint |
| 3 | blog_id | bigint |
Commentモデルの作成
$ rails g model Comment content:text user:references blog:references
アソシエーションの設定
app/models/user.rb
class User < ApplicationRecord has_many :comments, dependent: :destroy end
app/models/comment.rb
class Comment < ApplicationRecord belongs_to :user belongs_to :blog end
app/models/blog.rb
class Blog < ApplicationRecord has_many :comments, dependent: :destroy end
ルーティングの追加
Rails.application.routes.draw do
resources :blogs do
resources :comments
end
end
Commentコントローラーの設定
class CommentsController < ApplicationController
def create
@blog = Blog.find(params[:blog_id])
@comment = current_user.comments.build(comment_params)
@comment.blog_id = @blog.id
respond_to do |format|
if @comment.save
format.html { redirect_to blog_path(@blog) }
else
format.html { redirect_to blog_path(@blog) }
end
end
end
private
def comment_params
params.require(:comment).permit(:content, :blog_id)
end
end
フォームの作成
app/views/comments/_form.html.erb
<%= form_with(model: [blog, comment]) do |form| %>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
一覧画面の作成
app/views/comments/_index.html.erb
<% comments.each do |comment| %>
<% if comment.id.present? %>
<li>
<p><%= comment.content %></p>
</li>
<% end %>
<% end %>
ブログコントローラーの設定
app/controllers/blogs_controller.rb
class BlogsController < ApplicationController
def show
@comments = @blog.comments
@comment = @blog.comments.build
end
end
パーシャルの呼び出し
app/views/show.html.erb
<%= render partial: 'comments/index', locals: { comments: @comments, blog: @blog } %><%= render partial: 'comments/form', locals: { comment: @comment, blog: @blog } %>
以上で作成完了
