Polymorphic Associations in Rails

自作多情 提交于 2019-12-08 10:15:39

问题


How do polymorphic associations work in Rails? What are their advantages? Is there a way to add belongs_to method just by running a migration?


回答1:


Ryan has a railscast about this that is pretty good.

Belongs_to isn't something you add to a migration, you add it to the model. In the migration, you have to add the foreign key column. For example if you have a post model that belongs to a user, you'd add the user_id column to the post activerecord in a migration. Then you add

 belongs_to :user

in the post model separately. Then rails will do its magic in the background to give you the proxy collections in the user model.



来源:https://stackoverflow.com/questions/697840/polymorphic-associations-in-rails

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