kdt
kdt

Reputation: 28489

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?

Upvotes: 7

Views: 1345

Answers (2)

noodl
noodl

Reputation: 17408

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

Upvotes: 2

Mike Gorski
Mike Gorski

Reputation: 1228

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.

Upvotes: 8

Related Questions