コメントのDB作成と紐付け

<手順>

♡コメントのデータベースの作成し、DB側に制約をかける

♡userとboardモデルに紐付けをする

♡コメントモデルに制約を追加する

 

①コメントのデータベースを作成

rails g model Comment body:text user:references board:references

 

外部キー制約をする際はreferencesを用いるので、作成時のコマンドに入れる

文字数制限を60000字(仮)にする→limit: 60000を追記

bodyすなわち本文の入力なしでは登録できないようにする→null:falseを追記

 

class CreateComments < ActiveRecord::Migration[5.2]
  def change
    create_table :comments do |t|
      t.text :body, limit: 60000, null:false
      t.references :user, foreign_key: true
      t.references :board, foreign_key: true

      t.timestamps
    end
  end
end

②userとboardモデルに紐付けていく

☆app/models/comment.rb

①でgenerateした際に、referencesを用いたため、

自動的にbelongs_to :userbelongs_to :board

が作成されている。

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :board
end

app/models下のuser.rbとboard.rbに

has_many :comments, dependent: :destroy

を追加し、以下のようにする。

☆app/models/user.rb

class User < ApplicationRecord
  authenticates_with_sorcery!
  has_many :boards, dependent: :destroy
  has_many :comments, dependent: :destroy
end

☆app/models/board.rb

class Board < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
end

board.rbもuser.rbと紐付いているのでこんがらがる…。

③コメントモデルにバリデーションを追加する

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :board
  validates :body, presence: true, length: { maximum: 60_000 }
end