0

我很难找出正确的方法来设置这种关联。如何设置多态has_many:through?

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

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

需要有与不同的项目连接水平,并将当前水平是什么样的中介模式。

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

enter image description here

我之前问过类似的问题,但没有解释什么,我试图做一个彻底的可怕的工作,所以这是我的第二次尝试。

回答

1

ItemLevels需要一个种类就知道它是什么关联:然后

class ItemLevel < ActiveRecord::Base 
    # levelable_id :integer 
    # levelable_type :string(255) 
    belongs_to :levelable, :polymorphic => true 
    has_many :levels 
end 

class Musician < ActiveRecord::Base 
    has_many :levelables 
end 

class Musician < ActiveRecord::Base 
    has_many :levelables 
end 

class Manager < ActiveRecord::Base 
    has_many :levelables 
end 

级别只需要知道什么ItemLevel与其关联:

class Level < ActiveRecord::Base 
    belongs_to :item_level 
end 

如果你想成为严格,你应该在你的Level模型中加入一些验证来检查它是否有ItemLevel和被实例化的类型。