tkymtk's blog

Ruby on Rails及びその周辺について調べたこと。Do whatever you want to do at your own pace.

Rails4 外部キーをテーブルに設定するための、3通りのマイグレーションの書き方。

書き方

例として、micropostsテーブルにuser_idカラムを外部キーとして設定したいと思います。
(この例では、他にcontentカラムもテーブルに設定しています。)

普通に user_id カラムを作成
class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :content
      t.integer :user_id

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end
references を使う

referencesuser_idカラムを作成します。

class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :content
      t.references :user

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end
belongs_to を使う

belongs_toreferencesエイリアスです。

class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :content
      t.belongs_to :user

      t.timestamps
    end
    add_index :microposts, [:user_id, :created_at]
  end
end

具体的な使い方

例: Relationshipモデルを作成し、外部キーとしてfollower_idfollowed_idを作成し、その両方にindexを追加します。

referencesまたはbelongs_toを使わない
$ rails generate model Relationship follower_id:integer followed_id:integer

上記のコマンドで以下を生成

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end

    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
  end
end

以下の部分は手動で追加する必要があるところです。

add_index :relationships, :follower_id
add_index :relationships, :followed_id
referencesまたはbelongs_toを使う。
$ rails generate model Relationship follower:references followed:references

上記のコマンドで以下を生成

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.references :follower, index: true
      t.references :followed, index: true

      t.timestamps
    end
  end
end

一発。referencesbelongs_toに入れ替えても同じです。

別例

こんなこともできます。

$ rails generate migration AddUserRefToProducts user:references

上記のコマンドで以下を生成

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end

注意

referencesbelongs_toを使うときは、カラムネームを指定する際に_id接尾子をつけません。

リンク

広告

パーフェクト Ruby on Rails

パーフェクト Ruby on Rails

パーフェクトRuby (PERFECT SERIES 6)

パーフェクトRuby (PERFECT SERIES 6)

間違いがあれば、ご指摘下さると幸いです。