问题描述
如何多态协会Rails的工作?他们有什么优势?有没有办法只是通过运行迁移添加 belongs_to的
方法?
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?
推荐答案
瑞安有一个 railscast 一>这个是pretty不错。
Ryan has a railscast about this that is pretty good.
belongs_to的是不是你添加到迁移的东西,你把它添加到模型中。在迁移,您必须添加外键列。例如,如果你有一个属于用户的模式后,你会user_id列增加到帖子中的ActiveRecord迁移。然后添加
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
在后单独的模型。那么Rails会做它的魔力在后台给你的用户模型代理集合。
in the post model separately. Then rails will do its magic in the background to give you the proxy collections in the user model.
这篇关于多态关联Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!