LoginSignup
0
0

More than 3 years have passed since last update.

【Rails Guide】まとめ

Posted at

6. 2番めのモデルを追加する

app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :article
end

referencesキーワードは、モデルの特殊なデータ型を表す。
指定されたモデル名の後ろに_idを追加した名前を持つ新しいカラムをデーターベーステーブルに作成

db/schema.rb
class CreateComments <  ActiveRecord::Migration[6.0]
def change
  create_table :comments do |t|
    t.string :commenter
    t.text   :body
    t.references :article, null: false, foreign_key: true
    t.timestamps
  end
end
end 

t.references はarticle_idという名前のinteger型のカラムとインデックスとarticlesのidカラムを指す外部キー制約を設定する

dependent: :destroy
削除のオプション

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