【问题标题】:Rails 3 Abstract Class vs Inherited ClassRails 3 抽象类与继承类
【发布时间】:2011-03-02 15:03:56
【问题描述】:

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

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

提前感谢您的建议!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 inheritance abstract-class


    【解决方案1】:

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

    has_many :services
    has_many :products
    

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

    【讨论】:

      【解决方案2】:

      我都不会使用,并按照 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
      

      【讨论】:

      • 是的,抱歉,我的术语有点迟钝,我正在尝试创建一个视图,允许我的用户通过单个字段将项目添加到他们的商店。所以说一个包含所有项目(产品和服务)的组合框,所以我试图弄清楚如何对其进行建模。听起来这个协会会做我需要的。
      • 如果我理解正确的话,我可以做 storeObj.inventory_items.count 并获得商店中产品和服务的总数,因为加入模型?或者更重要的是,我可以通过 print_invoice_store_path(@inventory_items) 之类的操作打印所有产品和服务的发票?
      • 关于 store.inventory_items.count,是的,与任何 has_many 关联一样。 re print_invoice_store_path,这可能值得单独询问,但原则上也可以。不过,我想它更像 print_invoice_store_path(@store),然后您可以在操作中访问 @store.inventory_items。在任何情况下,您都可以使用相关的集合来处理或输出您喜欢的任何内容
      • 重新组合框的意图,是的,这应该适用。我没有发现这个问题很迟钝:) 清楚地了解界面以及您要完成的工作确实有很大帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多