【问题标题】:has_and_belongs_to_many or polymorphic has_many :through?has_and_belongs_to_many 或多态 has_many :through?
【发布时间】:2012-02-20 01:53:58
【问题描述】:

我无法找到建立此关联的正确方法。

我有 3 个模型:音乐家、乐队和经理。每一个都可以有一个与之相关的“水平”(压力、幸福等)。

但我不确定如何将我的 Levels 模型与其他 3 个正确关联。

我需要某种 has_many :through 那是多态的吗?我到底该如何设置呢?我还需要其他类型的关联吗?

【问题讨论】:

  • 澄清一下,关卡是与音乐家的实例还是所有音乐家相关联?

标签: ruby-on-rails model associations polymorphic-associations


【解决方案1】:

如果您要定义可以分配给特定模型类的属性,那么您可能希望使用更传统的方法。而不是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)
}

没有将模型与类关联而不是其他模型的实例的约定。

【讨论】:

    【解决方案2】:

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

    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
    

    您需要在 Levels 表中添加 leveled_typeleveled_id

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2011-06-06
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2012-08-23
      相关资源
      最近更新 更多