Rails 3 抽象类与继承类

发布于 2024-10-19 19:46:08 字数 291 浏览 2 评论 0原文

在我的 Rails 3 模型中,我有两个类:产品、服务。我希望两者都是 InventoryItem 类型,因为我有另一个名为 Store 和 Store has_many :InventoryItems 的模型,

这就是我想要达到的目标,但我不确定如何在我的 InventoryItem 模型以及我的产品和服务中对此进行建模模型。 InventoryItem 应该只是 Product 和 Service 继承的父类,还是应该将 InventoryItem 建模为 Product 和 Service 扩展的类抽象。

预先感谢您的建议!

In my rails 3 model, I have two classes: Product, Service. I want both to be of type InventoryItem because I have another model called Store and Store has_many :InventoryItems

This is what I'm trying to get to, but I'm not sure how to model this in my InventoryItem model and my Product and Service models. Should InventoryItem just be a parent class that Product and Service inherit from, or should InventoryItem be modeled as a class abstract of which Product and Service extend from.

Thanks in advance for the advice!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

放我走吧 2024-10-26 19:46:08

就我个人而言,我不会使用继承。你为什么不直接说

has_many :services
has_many :products

继承是相当昂贵的——无论是在运行时还是在可读性方面。这种情况听起来像是一个非常基本的情况,不需要继承。您真的希望产品和服务真正从基类继承某些东西吗?你所写的表明你只想建立关联。

Personally, I would not use inheritance. Why don't you just say

has_many :services
has_many :products

Inheritance is pretty expensive - both in terms of runtime and often in readability too. This case sounds like a very basic case for which no inheritance is required. Do you really want products and services to actually INHERIT something from a base class? What you writes indicates all you want is to establish the association.

喜爱纠缠 2024-10-26 19:46:08

我两者都不会使用,并遵循 Mörre 建议将 InventoryItem 作为连接模型:

class Store
  has_many :inventory_items
  has_many :products, :services, :through => :inventory_items
end

class InventoryItem
  belongs_to :store
  belongs_to :products, :services
end

class Product
  has_many :inventory_items
  has_many :stores, :through => :inventory_items
end

class Service
  has_many :inventory_items
  has_many :stores, :through => :inventory_items
end

I'd use neither, and follow what Mörre suggested to have InventoryItem be a join model:

class Store
  has_many :inventory_items
  has_many :products, :services, :through => :inventory_items
end

class InventoryItem
  belongs_to :store
  belongs_to :products, :services
end

class Product
  has_many :inventory_items
  has_many :stores, :through => :inventory_items
end

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