RoR:在这种情况下我应该使用belongs_to, :polymorphic吗?
我正在开发一个项目,其中许多 ActiveRecord 模型都可以有与之关联的对话。用户可以讨论网站的几乎各个方面。关于如何实施,我有两个想法。
1) 在资产中使用belongs_to,而不是对话 - 对话将完全不知道其资产
class Product< ActiveRecord::Base
belongs_to :conversation
end
class PurchaseOrder < ActiveRecord::Base
belongs_to :conversation
end
2) 使用belongs_to, :polymorphic =>;对话中正确
class Conversation < ActiveRecord::Base
belongs_to :asset, :polymorphic => true
end
class Product < ActiveRecord::Base
has_one :conversation, :as => :asset
end
class PurchaseOrder < ActiveRecord::Base
has_one :conversation, :as => :asset
end
建模这种关系的正确方法是什么?如果我要陈述这种关系,我会说“一个产品/采购订单可能有一个对话”。
I am working on a project where many ActiveRecord models can have a conversation associated with it. Users can discuss just about every aspect of the site. I have two ideas as to how this should be implemented.
1) Use a belongs_to in the asset, not the conversation - conversation will be totally unaware of its asset
class Product< ActiveRecord::Base
belongs_to :conversation
end
class PurchaseOrder < ActiveRecord::Base
belongs_to :conversation
end
2) Use a belongs_to, :polymorphic => true in the conversation
class Conversation < ActiveRecord::Base
belongs_to :asset, :polymorphic => true
end
class Product < ActiveRecord::Base
has_one :conversation, :as => :asset
end
class PurchaseOrder < ActiveRecord::Base
has_one :conversation, :as => :asset
end
Which is the correct way to model this relationship? If I were to state the relationship, I would say that "a product / purchase order may have one conversation".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这取决于关系中的一个模型需要了解另一个模型的哪些内容(如果有的话)。在我看来,从你的描述来看,第二种方法更适合这种情况。为什么?
Product
和PurchaseOrder
模型是自我约束的实体,因为它们可以独立于有关它们的对话而存在。因此,您可能不希望外键污染这些模型以进行对话。从这个意义上说,这种关系应该是不引人注目的。Conversation
对与其关联的实体具有逻辑依赖性,因此它具有asset_id
(和asset_type
)外键,这可能是合理的这是这是一个非常常见的问题,也是一个总是让我停下来思考的问题。这并不总是显而易见的。 这里有一篇很好的文章考虑了这个问题
I think it depends on what, if anything, one model in the relationship needs to know about the other. Seems to me, from your description that the second approach it more fitting in this case. Why?
Product
andPurchaseOrder
models are self-contrained entities in the sense that they can exist apart from conversations about them. So you probably don't want foreign keys polluting these models for tacking on conversations. The relationship ought to be unobtrusive in that sense.Conversation
has a logical dependency on the entity it's associated with so it has theasset_id
(andasset_type
) foreign keys and that's probably reasonableThis is a very common question and one which always has me stopping to think a bit too. It's not always obvious. There's a good article considering the issue here