Rails: is there a difference between 'references :foo' and 'integer :foo_id'?
When I use references :foo
in a migration, the column that's generated is called foo_id
. Is there actually any difference between doing references :foo
and just doing integer :foo_id
? Mayb开发者_如何学JAVAe something going on under the hood to enforce the relationship at the database level?
The result is the same for your specific case; you are correct. But references
allows for a :polymorphic => true
option which will automatically create the foo_type
column as a string in the table.
Semantically, references
is better if you are trying make your migrations better reflect the relations between tables in the database.
@Mike's answer nicely explains the meaning of references
. However, it's often better not to couple your migrations too closely to your AR associations. In particular, you can get in to all kinds of pickle when it comes to deploying your app if you run your migrations before updating the app from version control, for instance. It's not a big deal until it bites you :-)
精彩评论