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 を使う
references
はuser_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_to
はreferences
のエイリアスです。
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_id
とfollowed_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
一発。references
はbelongs_to
に入れ替えても同じです。
別例
こんなこともできます。
$ rails generate migration AddUserRefToProducts user:references
上記のコマンドで以下を生成
class AddUserRefToProducts < ActiveRecord::Migration def change add_reference :products, :user, index: true end end
注意
references
やbelongs_to
を使うときは、カラムネームを指定する際に_id
接尾子をつけません。
リンク
- Active Record Migrations — Ruby on Rails Guides
- ruby on rails - t.belongs_to in migration - Stack Overflow
広告
- 作者: すがわらまさのり,前島真一,近藤宇智朗,橋立友宏
- 出版社/メーカー: 技術評論社
- 発売日: 2014/06/06
- メディア: 大型本
- この商品を含むブログ (6件) を見る
- 作者: Rubyサポーターズ,すがわらまさのり,寺田玄太郎,三村益隆,近藤宇智朗,橋立友宏,関口亮一
- 出版社/メーカー: 技術評論社
- 発売日: 2013/08/10
- メディア: 大型本
- この商品を含むブログ (16件) を見る
- 作者: 高橋征義,後藤裕蔵,まつもとゆきひろ
- 出版社/メーカー: ソフトバンククリエイティブ
- 発売日: 2013/06/04
- メディア: 単行本
- この商品を含むブログ (26件) を見る