[Ruby on Rails] How to Add Foreign Key Columns to Other Tables (add_column, references)

Tadashi Shigeoka ·  Tue, May 8, 2012

In Ruby on Rails 3.2.2, I researched how to add columns that represent foreign keys to other tables, so here’s a memo.

For example, to add a column representing a foreign key to the Users table in a newly created Testers table, you can add it using the TableDefinition#references method.

rails g model tester title:string user:references

However, when adding a column representing a foreign key to the Users table to an existing table, you cannot use the references method.

rails g migration add_user_to_tester user:references

In this case, the foreign key should be defined as an integer type with a column name in the format “table_name_id”.

rails g migration add_user_id_to_tester user_id:integer

By the way, the migration file looks like this: (I also added an index for the foreign key)

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

That’s all from the Gemba.

【Reference】

activerecord - Rails 3 migrations: Adding reference column? - Stack Overflow