简体   繁体   English

多态与has_one,belongs_to的区别

[英]Difference in polymorphic and has_one, belongs_to

We have model called as Human having following column, name, password and behavior. 我们有名为Human的模型,具有以下列,名称,密码和行为。 we have another three models namely admins, receivers, donors whose fields varies according to the human behavior. 我们还有另外三种模型,即管理员,接收者,捐赠者,其领域随人类行为而变化。 Now I want to know whether I should use polymorphic associations or has_one belongs_to association? 现在,我想知道应该使用多态关联还是has_one相关性关联?

Your questions was a little unclear, but here's a general guide: 您的问题尚不清楚,但这是一个一般指南:

1) If it belongs to multiple other models, it should be polymorphic. 1)如果它属于多个其他模型,则应该是多态的。

2) If it only belongs to only one other model, it should belong_to that other model. 2)如果它仅属于另一个模型,则应属于该另一个模型。

3) If you're unsure of the future structure of your associations, polymorphic is a great bet because it can fit almost any structure, and it's fairly easy to undo. 3)如果您不确定关联的未来结构,那么多态是一个不错的选择,因为它几乎可以适应任何结构,并且撤消非常容易。

Let me know if you need any clarification. 让我知道您是否需要任何澄清。

Before answering this question we need to understand the polymorphic associations and has_one belongs_to associations first, 在回答这个问题之前,我们需要先了解多态关联和has_one所属关联到关联,

Polymorphic association: When we need to build association where a model is associated with more than one models we need to go for polymorphic. 多态关联:当我们需要建立一个模型与多个模型关联的关联时,我们需要进行多态关联。 quoting example from rails guide. 引用Rails指南中的示例。

    class Picture < ActiveRecord::Base
      belongs_to :imageable, polymorphic: true
    end

    class Employee < ActiveRecord::Base
      has_many :pictures, as: :imageable
    end

    class Product < ActiveRecord::Base
      has_many :pictures, as: :imageable
    end

Whereas when we have just one to one relationship between models and there is no association which associate from one model to second model and again some relation between first and third model then we can go for belongs_to and has_many associations. 而当我们在模型之间只有一对一的关系并且没有从一个模型到第二个模型的关联以及在第一个模型和第三个模型之间的某种关联的关联时,我们可以使用belongs_to和has_many关联。 Hope this clarify. 希望这个澄清。 let me know if more clarification needed. 让我知道是否需要进一步澄清。

More Here 这里更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM