LoginSignup
1
3

More than 3 years have passed since last update.

【48日目】【技術日記】コメント機能の作成 アソシエーションとかパーシャルとか

Posted at

ここ数日は新しくお願いしたメンターさんとの面談や、
そのメンタリングの中で出された課題などを行なっていたので技術に触れていなかったため更新中断しておりました。
今日からまた技術の学習を進めていきます。

なお今日はトピックというよりは、学習ログの掲載という感じになります。
主にアソシエーションの設定であったり、掲示板のコメントフォームのパーシャルの作成部分になります。
コメントフォームはviewを持たないので、親であるboardと紐づいた形で、@commentを作るところなんかが自分では思いつけない部分だと思いました。
まだ完璧に理解できていないと思います。

65 Commentモデルの作成とアソシエーション

Commentモデルの作成

Commentモデルのマイグレーションファイルを作成

docker-compose exec web bundle exec rails g model comment board:references name:strings comment:text 
# rails g model モデル名 親テーブル名:references カラム名:型
# referencesによって「親テーブル名_id」という外部キーカラムが作成され、アソシエーションされる

出来上がったマイグレーションファイルは下記

comments.rb
class CreateComments < ActiveRecord::Migration[5.0]
    def change
        create_table :comments do |t|
            t.references :board, foreign_key: true # 引数によって親テーブルにないidが保存できなくなる
            t.string :name, null: false #引数によってnullの場合エラーとなる
            t.text :comment, null: false

            t.timestamps
        end
    end
end

マイグレートを実行し、DBにマイグレーション内容を反映

docker-compose exec web bundle exec rake db:migrate

アソシエーションの設定

親テーブル

ApplicationRecordのクラス継承の下に

board.rb
has_many :comments
#1対他のためhas_many:子テーブル名(複数形)

子テーブル

comments.rb
belongs_to :board

66 コメント書き込み機能のルーティング追加 &コントローラ作成

コメントコントローラの作成

コメント機能には作成と削除のみを付与する。
また、コメントページは用意せず、掲示板のshowの下部に表示する。

docker-compose exec web rails g controller comments create destroy --skip-template-engine
# viewの作成をskipする

ルーティングの修正

rails g によって自動的にルーティングされるが、リソースベースルーティングに合わせて修正する。

routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
    resources :boards
    resources :comments, only: %i[create destroy]
end

コメントオブジェクトの作成

form_forヘルパーでコメントのフォームを作成するために、board_controllerのshowメソッドで@commentオブジェクトを作成する。
ただし、何かしらの方法で掲示板とコメントを紐付ける必要がある。

boards_controller.rb
def show
@comment = @board.comments.new
binding.pry
end

boardオブジェクトのcommentにnew メソッドを呼び出すことで掲示板に紐ついた@commentが作成できる。
binding.pryで@board.commentsの中を見ておく。
ちなみにこのオブジェクトのクラスはComment::ActiveRecord_Associations_CollectionProxy

67 コメントフォームの作成

show の修正

パーシャルを用いて作成

show.html.erb
<%= render 'boards/detail', detail: @detail %>
<%= render partial: 'comment_form', locals: { comment: @comment} %>
# commentというローカル変数で@commentのオブジェクトを渡すようにしている

パーシャルの作成

_comments_form.html.erb
<div class="p-comment__formBox">
<p class="p-comment__formTitle">コメント記入</p>
    <%= form_for comment do |f| %>
        <%= f.hidden_field :board_id %>
          # フォームの内容と一緒に外部キーを渡すために必要になる
          # フォーム自体は存在しない
        <div class="form-group">
            <%= f.label :name, '名前' %>
            <%= f.text_field :name, class: 'form-control' %>
        </div>
        <div class="form-group">
            <%= f.label :comment, 'コメント' %>
            <%= f.text_area :comment, class: 'form-control', rows: 4 %>
        </div>
        <%= f.submit '送信', class: 'btn btn-primary' %>
    <% end %>
</div>

CSSの作成

comments.scss
.p-comment__formBox {
    margin: 30px auto;
    border: 5px solid #e8e8e8;
    padding: 25px;
    border-radius: 14px;
}

.p-comment__formTitle {
    border-bottom: 2px solid #dfdfdf;
    padding-bottom: 5px;
}

これだけでは読み込まれないので、application.scssでインポートするよう追記

applocateion.scss
@import "comments"

68 コメント保存処理の実装

rails-flogの導入

binding.pryのログを見やすくしてくれるらしい。
明日から使っていくことになる。

gem 'rails-flog', require 'flog'
1
3
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
1
3