has_many:through,嵌套的多态关系

时间:2009-09-08 01:51:05

标签: ruby-on-rails ruby activerecord polymorphism

有没有办法直接引用(直接使用rails,而不需要使用大量的自定义SQL)嵌套在多态关系背后的关系?在下面的示例中,有没有办法在User中定义引用LayerTwo的has_many关系?

我想做(在用户中)

has_many :layer_twos, :through => layer_ones

但是这种方法没有通过多态关系考虑先前指定的has_many关系。有什么建议?它可能不是通过现有的铁路惯例,但我认为我会把问题推迟给那些比我更聪明的人。

class CreateOwners < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.timestamps
    end
    create_table :owners do |t|
      t.timestamps
      t.references :owned, :polymorphic => :true
      t.references :user
    end     
    create_table :layer_ones do |t|
    end
    create_table :layer_twos do |t|
      t.references :layer_one
    end
  end
end


class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :owned, :polymorphic => true
end

class User < ActiveRecord::Base
  has_many :owners
  has_many :layer_ones, :through => :owners, :source => :owned, :source_type => 'LayerOne'
end

class LayerOne < ActiveRecord::Base
  has_many :owners, :as => :owned
  has_many :layer_twos
end

class LayerTwo < ActiveRecord::Base
  belongs_to :LayerOne
end

4 个答案:

答案 0 :(得分:2)

现在应该注意,Rails 3.1嵌入了has_many:通过内置的关联。an ASCIIcast on this

答案 1 :(得分:1)

据我所知,ActiveRecord不支持:通过:通过关系。您可以使用一些技巧和黑客来解决这个问题,例如创建一个将关系重新映射为更直接的VIEW,这可以简化您的ActiveRecord模型而牺牲数据库的复杂性。

多态性关联特别令人讨厌。

答案 2 :(得分:1)

我不确定它是否支持通过多态协作进行嵌套,但是可能值得查看nested_has_many_through插件,该插件来自自述文件:

  

...可以定义   has_many :through这种关系   浏览其他has_many :through   关系,可能通过   任意深层次。这个   允许任何数量的关联   要构建的表,没有   不得不诉诸find_by_sql(其中   如果您需要,不是一个合适的解决方案   通过:include进行急切加载   同样)。

答案 3 :(得分:0)

试试这个(Rails 3):

class LayerOne < ActiveRecord::Base
  class << self
    def layer_twos
      LayerTwo.where(:layer_one_id => all.map(&:id))
    end
  end
end