【问题标题】:How to set up a polymorphic has_many :through?如何设置多态 has_many :through?
【发布时间】:2012-02-20 13:07:02
【问题描述】:
我无法找到建立此关联的正确方法。
我有 3 个模型:音乐家、乐队和经理。每一个都可以有一个与之相关的“水平”(压力、幸福等)。
但我不确定如何正确地将我的关卡与其他 3 个关卡相关联。
需要有一个中间模型,将关卡与不同的项目联系起来,并设置当前关卡的位置。
我需要某种 has_many :through 那是多态的吗?我到底该如何设置呢?我还需要其他类型的关联吗?
我之前问过一个类似的问题,但在解释我想要做什么方面做得非常糟糕,所以这是我的第二次尝试。
【问题讨论】:
标签:
ruby-on-rails
model
associations
polymorphic-associations
【解决方案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
Level 然后只需要知道它关联的 ItemLevel 是什么:
class Level < ActiveRecord::Base
belongs_to :item_level
end
如果你想严格,你应该在你的 Level 模型中进行一些验证,以检查它是否具有 ItemLevel 和被实例化的类型。