LoginSignup
278
241

More than 5 years have passed since last update.

外部キーをreferences型カラムで保存する

Last updated at Posted at 2015-09-01

使い方

refernces型は外部キーを追加する時に使います
今回はtweetsモデルにuser_idを追加します。(user has_many tweet)

class CreateTweets < ActiveRecord::Migration
  def change
    create_table :tweets do |t|
      t.string :text
      t.references :user

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

belongs_toreferencesのエイリアスなので、

t.references :user

t.belongs_to :user

とすることもできます。

実践例

テーブル作成時

rails g model Tweet user:references
とすれば、

class CreateTweets < ActiveRecord::Migration
  def change
    create_table :tweets do |t|
      t.references :user, index: true

      t.timestamps
    end
  end
end

一発で出してくれます。ちなみにreferencesbelongs_toに入れ替えても同じです。

カラム追加時

rails g migration AddUserRefToTweets user:references

で、

class AddUserRefToTweets < ActiveRecord::Migration
  def change
    add_reference :tweets, :user, index: true
  end
end

とできます。

注意

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

参考

278
241
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
278
241