代码之家  ›  专栏  ›  技术社区  ›  GarlicFries

多态关联在这里合适吗?

  •  1
  • GarlicFries  · 技术社区  · 15 年前

    class Widget < ActiveRecord::Base
      has_one :widget_layout
    end
    
    class WidgetLayout < ActiveRecord::Base
      belongs_to :widget
      belongs_to :layoutable, :polymorphic => true
    end
    
    class InformationalLayout < WidgetLayout
      has_one :widget_layout, :as => :layoutable
    end
    
    class OneWayCommunicationLayout < WidgetLayout
      has_one :widget_layout, :as => :layoutable
    end
    

    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
    

    在这里,“拥有”模型(产品或员工)可以是许多类中的一个。我希望“owned”模型是许多类中的一个,所有这些类都从另一个类继承基本行为。此外,所有这些子类的行为都非常不同,因此STI的效率非常低。我在这里迷路了…我很感激你能给我的任何帮助!

    编辑:只是为了澄清我想做什么。。。我有一个叫做Widget的“拥有”类。一个小部件代表了一个非常简单的web应用程序。每个小部件可以通过几个不同的布局中的一个来表示。因此,我定义了这些不同的布局类。这些布局在外观和行为上都有很大的不同,但它们确实共享一些共同的功能。因此,我想将这种常见行为提取到WidgetLayout类中,它们可以从中继承。最后,任何小部件都可以关联到一个“特定”的布局(可以是信息性的,单向通信等),我只是不确定这个设置应该如何构造。

    编辑(我希望是最后一个!):啊,再看看你的例子,我明白了。我唯一缺少的就是让布局继承普通行为。那么,你喜欢这工作吗?:

    class Widget < ActiveRecord::Base
      belongs_to :layout, :polymorphic => true
    end
    
    class InformationalLayout < WidgetLayout
      has_many :widgets, :as => :layout
    end
    
    class OneWayCommunicationLayout < WidgetLayout
      has_many :widgets, :as => :layout
    end
    
    class WidgetLayout < ActiveRecord::Base
      # Define common behaviour here
    end
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   mark    15 年前

    你的要求和你发布的例子不符有什么原因吗?

    class Widget < ActiveRecord::Base
      belongs_to :layout, :polymorphic => true
    end
    
    class InformationalLayout < DefaultLayout
      has_many :widgets, :as => :layout
    end
    
    class OneWayCommunicationLayout < DefaultLayout
      has_many :widgets, :as => :layout
    end
    
    def DefaultLayout < ActiveRecord::Base
     #no relationship here, only class inheritance 
    
      def get_sorted_data
        return 'example data'
      end
    end
    
    # eg
    widget.find(1).layout.class => InformationalLayout
    widget.find(2).layout.class => OneWayCommunicationLayout
    
    widget.find(1).layout.get_sorted_data => 'example data'
    widget.find(2).layout.get_sorted_data => 'example data'