LoginSignup
1
2

More than 5 years have passed since last update.

【rails5】テーブルに複数の外部キーを追加する

Last updated at Posted at 2019-02-15

テーブルに複数の外部キー(foreign_key)を追加する

パターン1、モデル生成時に、外部キーを生成する

1、Invitationテーブル作成。
2、user_idとproject_idカラムを生成し、両方のforeign_keyも生成出来る

フォーマット

rails g モデル名 参照先モデル名:references
複数でも同様
rails g モデル名 参照先モデル名:references 参照先モデル名:references
同時に他のカラムも追加
rails g モデル名 参照先モデル名:references 参照先モデル名:references カラム名:型

rails g model Invitation user:references  project:references destination_mail:string

パターン2、モデル生成した後に外部キーを追加する


Issuesテーブル作成

rails g model Issues title:string created_user_id:integer project_id:integer assigned_user_id:integer description:text status:string deleted_at:timestamp

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

class CreateIssues < ActiveRecord::Migration[5.2]
  def change
    create_table :issues do |t|
      t.string :title
      t.integer :created_user_id
      t.integer :project_id
      t.integer :assigned_user_id
      t.text :description
      t.string :status, default: 'open'
      t.timestamp :deleted_at

      t.timestamps
    end
  end
end

例、issuesテーブルに、2つの外部キー(created_user_idと、project_id)を追加する場合

フォーマット
add_foreign_key :参照元のテーブル名, :参照したいテーブル名, column: :参照元につける外部キー名
add_foreign_key :issues, :users, column: :created_user_id
add_foreign_key :issues, :projects, column: :project_id
1
2
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
2