ギークなエンジニアを目指す男

機械学習系の知識を蓄えようとするブログ

ドットインストールで作るブログアプリその8(RubyonRails)

例のごとくドットインストールのRails5の動画を元に学んでいきます!
前回までは記事の編集処理の実装まで行ったので
本日はブログの記事にコメントが登録できるような処理の追加を行います!(23章あたりからです)
前回同様、Githubへのソースコードアップもします。

前回記事はこちら

taxa-program.hatenablog.com

Comment モデルの作成

下記コマンドでmodelの作成を行います。

 $rails g model Comment body:string post:references

ここでのポイントは、postに紐づけるためにreferences特性を付与していることです。(Commentは単数形です)

そのあとはお決まりのmigrateをしましょう。

 $rails db:migrate

これでコメントmodelが作成されたことが分かると思います。
app/models/comment.rb

class Comment < ApplicationRecord
  # postに紐づいていることが記載されている
  belongs_to :post
  # バリデーションを設定
  validates :body, presence: true
end

さらに、下記ファイルも修正します。

app/models/post.rb

class Post < ApplicationRecord
  # 下記の様に記述しておくと、@post.comments でpostに紐づくコメントが取得できる
  has_many :comments

  # 必須チェック(presence)と文字数(length)チェック及びエラーメッセージの設定
  validates :title, presence: true, length:{ minimum: 3, message: 'Too short to post!!' }
  validates :body, presence: true
end

ルーティングの設定

モデルの追加が終了したら、ルーティングの設定を行います。

config/routes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :posts do
    # ルーティングに追加
    resources :comments
  end

  root 'posts#index'
end

上記記述を追加したあとに、ルーティングを確認してみると

           Prefix Verb   URI Pattern                                 Controller#Action
    post_comments GET    /posts/:post_id/comments(.:format)          comments#index
                  POST   /posts/:post_id/comments(.:format)          comments#create
 new_post_comment GET    /posts/:post_id/comments/new(.:format)      comments#new
edit_post_comment GET    /posts/:post_id/comments/:id/edit(.:format) comments#edit
     post_comment GET    /posts/:post_id/comments/:id(.:format)      comments#show
                  PATCH  /posts/:post_id/comments/:id(.:format)      comments#update
                  PUT    /posts/:post_id/comments/:id(.:format)      comments#update
                  DELETE /posts/:post_id/comments/:id(.:format)      comments#destroy
            posts GET    /posts(.:format)                            posts#index
                  POST   /posts(.:format)                            posts#create
         new_post GET    /posts/new(.:format)                        posts#new
        edit_post GET    /posts/:id/edit(.:format)                   posts#edit

             post GET    /posts/:id(.:format)                        posts#show
                  PATCH  /posts/:id(.:format)                        posts#update
                  PUT    /posts/:id(.:format)                        posts#update
                  DELETE /posts/:id(.:format)                        posts#destroy
             root GET    /                                           posts#index

上記のようにcommentsへのルートが設定されていることが分かると思います。

Commentsコントローラの作成

次にコントローラを作成していきます。

 $ rails g controller Comments

ここはCommentsのように複数形であることに注意です。

コメントは記事詳細画面から追加できるようにするため、
下記ファイルに処理を記述します。
app/views/posts/show.html.erb

<!-- コメントの作成 -->
<h3>Comments</h3>
<%= form_for ([@post, @post.comments.build]) do |f| %>
<!-- タイトルcolumnに対応するフィールド -->
<p>
    <%= f.text_field :body %>
</p>
<p>
    <%= f.submit %>
</p>

コメントを保存するActionの作成

下記ファイルを修正していきます。
app/controllers/comments_controller.rb

class CommentsController < ApplicationController

  def create
    #ルーティングを確認すると、comments#createには:post_idが渡ってくることが分かるため
    # params[:post_id]を記載
    @post = Post.find(params[:post_id])
    @post.comments.create(comment_params)
    # 記事の詳細画面にリダイレクト
    redirect_to post_path(@post)
  end

  private
    # ストロングパラメータ
    def comment_params
      params.require(:comment).permit(:body)
    end

end

登録したコメントを表示させる

さらに記事詳細画面に記述を加えます。
app/views/posts/show.html.erb

<!-- ポストのコメントが存在していれば -->
<% if @post.comments.any? %>
<ul>
  <% @post.comments.each do |comment| %>
  <li>
    <%= comment.body %>
  </li>
  <% end %>
</ul>
<% end %>

ここまでで、記事に対してコメントを追加し、
そのコメントを画面に表示させることができたと思います。

ここまで長かったですが、残りあと少しです。
次回はコメントの削除と、全体的な見直しを行い、
ドットインストールでのRails学習記事を終了したいと思います。

ここまでのソースは下記に置いてあります。

github.com