Specifying column name in a "references" migration

I want to make a migration in Rails, referencing another table. Usually, I would do something like:

add_column :post, :user, :references

This creates a column named user_id in posts table. But what if, instead of user_id, I want something like author_id? How can I do that?


Solution 1:

For Rails 5+

Initial Definition:

If you are defining your Post model table, you can set references, index and foreign_key in one line:

t.references :author, index: true, foreign_key: { to_table: :users }

Update Existing:

If you are adding references to an existing table, you can do this:

add_reference :posts, :author, foreign_key: { to_table: :users }

Note: The default value for index is true.

Solution 2:

In Rails 4.2+ you can also set foreign keys in the db as well, which is a great idea.

For simple associations this can be done also on t.references adding foreign_key: true, but in this case you'll need two lines.

# The migration
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id

# The model
belongs_to :author, class_name: "User"

Solution 3:

In rails 4, when using postgresql and the schema_plus gem you can just write

add_reference :posts, :author, references: :users

This will create a column author_id, which correctly refers to users(id).

And in your model, you write

belongs_to :author, class_name: "User"

Note, when creating a new table you can write it as follows:

create_table :things do |t| 
  t.belongs_to :author, references: :users 
end 

Note: the schema_plus gem in it's entirety is not compatible with rails 5+, but this functionality is offered by the gem schema_auto_foreign_keys (part of schema_plus) which is compatible with rails 5.