Specifying column name in a "references" migration

caarlos0 picture caarlos0 · Dec 4, 2012 · Viewed 70.5k times · Source

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?

Answer

Sheharyar picture Sheharyar · Feb 5, 2017

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.