LoginSignup
44
38

More than 3 years have passed since last update.

reference型のカラムを作成、追加する時の気をつける点

Posted at

はじめに

テーブルにreference型のカラムを追加する際に、マイグレーションファイルの
記述方法に細かな作法があるようなのでまとめておきます。

テーブルと一緒にreference型のカラムを作成する時

前提条件

  • userテーブルがあり、新たにcredit_cardテーブルを作る
  • credit_cardテーブルの中にはreference型のuser_idカラムがある。
  • 他のカラムとして、カード番号、期限、セキュリティ番号がある。

credit_cardモデルを作成

$ rails g model credit_card

作られたmigrationファイルを開き、編集

db/migrate/作成された日付_create_creditcards.rb

class CreateCreditcards < ActiveRecord::Migration[5.2]
  def change
    create_table :creditcards do |t|
      t.integer :credit_number, null: false
      t.integer :limit_month, null: false
      t.integer :limit_year, null: false
      t.integer :security_number, null: false
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end

マイグレーションの実行

$ rake db:migrate

すでに作られているテーブルにreference型のカラムを追加するとき

前提条件

  • userテーブルとcredit_cardテーブルがある
  • credit_cardテーブルにはカード番号、期限、セキュリティ番号のカラムがある
  • 新たにreference型のuser_idというカラムを追加する

マイグレーションファイルの生成

$ rails g migration AddReferencesToCredit_cards

作られたmigrationファイルを開き、編集

db/migrate/作成された日付_add_references_to_credit_cards.rb

class AddReferencesToCreditCards < ActiveRecord::Migration[5.2]
  def change
    add_reference :credit_cards, :user, null: false, foreign_key: true
  end
end

マイグレーションの実行

$ rake db:migrate

ポイント

  • 作成する時は、references
  • 追加する時は、reference
  • 追加する際の対象テーブルの名前は複数形
  • user_idカラムを作る時のカラム名の指定は、:userのみ(_idをつけない)
44
38
1

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
44
38