これまでに作った機能について簡単にまとめていく。
今回は、
コメント機能の作成
前提条件
何かのモデルの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モデルの作成
1 |
$ rails g model Comment content:text user:references blog:references |
アソシエーションの設定
app/models/user.rb
1 2 3 |
class User < ApplicationRecord has_many :comments, dependent: :destroy end |
app/models/comment.rb
1 2 3 4 |
class Comment < ApplicationRecord belongs_to :user belongs_to :blog end |
app/models/blog.rb
1 2 3 |
class Blog < ApplicationRecord has_many :comments, dependent: :destroy end |
ルーティングの追加
1 2 3 4 5 |
Rails.application.routes.draw do resources :blogs do resources :comments end end |
Commentコントローラーの設定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
<%= 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
1 2 3 4 5 6 7 |
<% comments.each do |comment| %> <% if comment.id.present? %> <li> <p><%= comment.content %></p> </li> <% end %> <% end %> |
ブログコントローラーの設定
app/controllers/blogs_controller.rb
1 2 3 4 5 6 7 8 |
class BlogsController < ApplicationController def show @comments = @blog.comments @comment = @blog.comments.build end end |
パーシャルの呼び出し
app/views/show.html.erb
1 2 3 4 5 |
<div id="comments_area"> <%= render partial: 'comments/index', locals: { comments: @comments, blog: @blog } %> </div> <%= render partial: 'comments/form', locals: { comment: @comment, blog: @blog } %> |
以上で作成完了