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?
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 }
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.