Rails: is there a difference between 'references :foo' and 'integer :foo_id'?

社会主义新天地 提交于 2019-12-22 04:55:23

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4736879/rails-is-there-a-difference-between-references-foo-and-integer-foo-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!