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

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?

This question is related to ruby-on-rails activerecord migration

The answer is


You can add references to your model through command line in the following manner:

rails g migration add_column_to_tester user_id:integer

This will generate a migration file like :

class AddColumnToTesters < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
  end
end

This works fine every time i use it..


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

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

Please note that you will most likely need an index on that column too.

class AddUserReferenceToTester < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
    add_index  :testers, :user_id
  end
end

That will do the trick:

rails g migration add_user_to_tester user_id:integer:index

When adding a column you need to make that column an integer and if possible stick with rails conventions. So for your case I am assuming you already have a Tester and User models, and testers and users tables.

To add the foreign key you need to create an integer column with the name user_id (convention):

add_column :tester, :user_id, :integer

Then add a belongs_to to the tester model:

class Tester < ActiveRecord::Base
  belongs_to :user
end

And you might also want to add an index for the foreign key (this is something the references already does for you):

add_index :tester, :user_id

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


You can use references in a change migration. This is valid Rails 3.2.13 code:

class AddUserToTester < ActiveRecord::Migration
  def change
    change_table :testers do |t|
      t.references :user, index: true 
    end
  end
  def down
    change_table :testers do |t|
      t.remove :user_id
    end
  end
end

c.f.: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table


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
      end
  end

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 

generates:

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

http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration

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
end

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'}
end

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

http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration


Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to activerecord

Empty brackets '[]' appearing when using .where Get only records created today in laravel How do you manually execute SQL commands in Ruby On Rails using NuoDB Rails 4 LIKE query - ActiveRecord adds quotes Rails create or update magic? CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column? Check if record exists from controller in Rails Codeigniter's `where` and `or_where` Codeigniter LIKE with wildcard(%) Codeigniter: does $this->db->last_query(); execute a query?

Examples related to migration

Want to upgrade project from Angular v5 to Angular v6 Laravel 5.4 Specific Table Migration SQLSTATE[HY000] [2002] Connection refused within Laravel homestead Laravel migration table field's type change How can I rename column in laravel using migration? Warning about `$HTTP_RAW_POST_DATA` being deprecated Entity Framework rollback and remove bad migration Migration: Cannot add foreign key constraint Maven is not working in Java 8 when Javadoc tags are incomplete Rails: Adding an index after adding column