Rails 4.2 finally added native support for database-level foreign keys, which is great. You can write the following code in a migration (assuming the presence of a users
table):
And Rails will apply its conventions and infer what you expect:
We have a database-level foreign key pointing from the user_id
column of the posts
table, to the id
column of the posts
table. You can specify all of the expected options for the foreign key - on_delete
, on_cascade
, etc. This will work just fine in both PostgreSQL and MySQL - it’s a no-op in every other ActiveRecord adapter (including SQLite!)
The problem is when you want to name your associations and columns more semantically - a post doesn’t have a user, it has an author. So you generate your model nicely on the command line:
Which generates a migration that includes:
This will error out when you try to run the migration:
Rails’ automatic inference has failed - it doesn’t know that our author
association is actually to the users
table.
To fix this, you can modify the migration before running it, and configure which column the foreign key should use, and which table the key should point to:
And then the foreign key is created as you would expect:
Success! Rails can do some amazing things when it comes to following its conventions, but sometimes it requires a little help to take full advantage of the functionality it provides. I hope this helps someone!