RoR:在这种情况下我应该使用belongs_to, :polymorphic吗?

发布于 2024-09-10 12:46:36 字数 699 浏览 5 评论 0原文

我正在开发一个项目,其中许多 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2024-09-17 12:46:36

我认为这取决于关系中的一个模型需要了解另一个模型的哪些内容(如果有的话)。在我看来,从你的描述来看,第二种方法更适合这种情况。为什么?

  • ProductPurchaseOrder 模型是自我约束的实体,因为它们可以独立于有关它们的对话而存在。因此,您可能不希望外键污染这些模型以进行对话。从这个意义上说,这种关系应该是不引人注目的。
  • 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?

  • The Product and PurchaseOrder 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.
  • A Conversation has a logical dependency on the entity it's associated with so it has the asset_id (and asset_type) foreign keys and that's probably reasonable

This 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文