1

这里就是我想:这里是一个多态关联吗?

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 

我敢肯定这是完全错误的。我试图做的事情似乎与我看到多态关联所展现出来的相反。例如,从Rails指南:

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 

这里“拥有”模型(产品或员工)可以是许多类之一。我希望“拥有”模型是许多类中的一个,它们都继承了另一个类的基本行为。另外,所有这些小类的行为都有很大的不同,STI会非常低效。我很迷茫......我感谢你能给予的任何帮助!

编辑:只是为了澄清我想要做什么......我有一个“拥有”类叫Widget。一个小部件代表了一些非常简单的网络应用程序。每个小部件可以通过几种不同布局中的一种来表示。因此,我正在定义这些不同的布局类。布局可以在外观和行为方面有很大的不同,但它们确实有共同的功能。正因为如此,我想将这些常见的行为从它们可以继承的WidgetLayout类中提取出来。最后,任何Widget都可以关联到一个“特定”布局(无论是Informational,OneWayCommunication等)。我只是不确定这个设置应该如何构造。编辑(最后一个,我希望!):啊,再看看你的例子,我看到它。我唯一缺少的是布局继承了常见的行为。那么,像这样的工作吗?:

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

是否有一个原因,你的要求不符合你发布的例子?

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' 
+0

我很困惑 - 我的哪些要求与我给出的例子不符?我并不是说他们确实需要,只是说我不明白你的意思。我会编辑这个帖子来澄清我自己 - 希望有所帮助。 – GarlicFries 2010-09-09 21:53:50

+0

嗨Brennon。我编辑了我的答案。我可以问,什么是布局?我想问的原因是布局听起来有点像查看(html等)。 – mark 2010-09-10 08:36:19

+0

已经死了......谢谢,马克。布局是一个令人困惑的类名,我知道。重命名它可能是最好的,因为它与布局/视图的Rails想法完全无关。这个Rails应用程序将最终生成小部件(即iGoogle,Mac Dashboard,Opera Widgets等),并且这些类将用于产生小部件的几种不同的一般类型(布局)的规范。因此,它们在内部与Rails应用程序完全没有关系。我想应该在那里更具描述性。模板也不行,我想! :) – GarlicFries 2010-09-10 08:58:11