2

我很难搞清楚设置这种关联的正确方法。has_and_belongs_to_many或多态has_many:通过?

我有3个模特:音乐家,乐队和经理。每个人都可以有一个与他们相关的“水平”(压力,快乐等)。

但我不知道如何正确地关联我水平模型与其他3

我需要某种形式的has_many的:通过这就是多态?我究竟如何设置它?有一些其他类型的相关我需要吗?

enter image description here

+0

澄清,是一个关联的级别,说一个音乐家的实例,或所有音乐家? – bdon 2012-02-20 02:07:52

回答

0

如果这就是你定义可以分配到特定的类模型的属性的话,那么你可能想使用更传统的方法。而不是kind使用类似record_type的东西,并在其上构建一个范围。

那么你要做的是获取它们是在你的任何实体和这个列之间创建一个存取方法,而不是关系。事情是这样的:

def levels 
    Level.for_record_type(self.class) 
end 

for_record_type是一个范围:

scope :for_record_type, lambda { |record_type| 
    where(:record_type => record_type.to_s) 
} 

有没有约定型号,类别,而不是其他车型的实例相关联。

0

是的,这将是一个多态关联:

class Level < ActiveRecord::Base 
    belongs_to :leveled, :polymorphic => true # maybe there's a better word than "leveled" 
end 

class Musician < ActiveRecord::Base 
    has_many :levels, :as => :leveled 
end 

你需要一个leveled_typeleveled_id添加到您的等级表。