[Ruby-on-rails] Rails 3 migrations: Adding reference column?


EDIT: This is an outdated answer and should not be applied for Rails 4.x+

You don't need to add references when you can use an integer id to your referenced class.

I'd say the advantage of using references instead of a plain integer is that the model will be predefined with belongs_to and since the model is already created and will not be affected when you migrate something existing, the purpose is kind of lost.

So I would do like this instead:

rails g migration add_user_id_to_tester user_id:integer

And then manually add belongs_to :user in the Tester model


If I create a new rails 3 migration with (for example)

rails g migration tester title:tester user:references

, everything works fine...however if I add a column with something along the lines of:

rails g migration add_user_to_tester user:references

the reference field is not recognised. In short, the question is: how do I add a referencing column to a rails migration from the command line?

That will do the trick:

rails g migration add_user_to_tester user_id:integer:index

Running rails g migration AddUserRefToSponsors user:references will generate the following migration:

def change
  add_reference :sponsors, :user, index: true

For Rails 4

The generator accepts column type as references (also available as belongs_to).

This migration will create a user_id column and appropriate index:

$ rails g migration AddUserRefToProducts user:references 


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


For Rails 3

Helper is called references (also available as belongs_to).

This migration will create a category_id column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id for you.

change_table :products do |t|
  t.references :category

If you have polymorphic belongs_to associations then references will add both of the columns required:

change_table :products do |t|
  t.references :attachment, :polymorphic => {:default => 'Photo'}

Will add an attachment_id column and a string attachment_type column with a default value of Photo.


With the two previous steps stated above, you're still missing the foreign key constraint. This should work:

  class AddUserReferenceToTester < ActiveRecord::Migration
      def change
          add_column :testers, :user_id, :integer, references: :users