Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Maybe something going on under the hood to enforce the relationship at the database level?

like image 318
kdt Avatar asked Jan 19 '11 15:01

kdt


2 Answers

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.

like image 111
Mike Gorski Avatar answered Sep 21 '22 00:09

Mike Gorski


@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 :-)

like image 24
noodl Avatar answered Sep 19 '22 00:09

noodl