LoginSignup
0
0

データベースにアソシエーションを設定する

Posted at

(dockerを使っているのでターミナルのコマンドにdockerが入っていたりします・・)

generateコマンドを使ってBoardモデルを作成する

rails g model Board user_id:integer title:string body:text

データベースにusersテーブルを作るためのマイグレーションファイルと、Userモデルが作成される。

マイグレーションファイルを編集する。

(空欄を許可しない設定を追加)

class CreateBoards < ActiveRecord::Migration[7.0]
  def change
    create_table :boards do |t|
      t.integer :user_id
      t.string :title, null: false
      t.text :body, null: false

      t.timestamps
    end
  end
end

マイグレーションを実行して、データベースにusersテーブルを作成する

docker compose run web rails db:migrate 

docker compose run web rails db:migrate:status コマンドを実行し、先ほどのマイグレーションファイルが適用されている状態(Statusがup状態)になっていることを確認

Status   Migration ID    Migration Name
--------------------------------------------------
   up     20240123074239  Create boards

models/board.rbにバリデーションを追加

class Board < ApplicationRecord

  validates :title, presence: true, length: { maximum: 255 }
  validates :body, presence: true, length: { maximum: 65535 }
end

アソシエーションを定義
models/board.rb

class Board < ApplicationRecord
  belongs_to :user
end

models/user.rbには以下の記載を追加

class User < ApplicationRecord

  has_many :boards, dependent: :destroy
end
0
0
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
0
0