繁体   English   中英

has_many:through,嵌套的多态关系

[英]has_many :through, nested polymorphic relations

有没有一种方法可以直接引用(直接使用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

现在应该注意的是,Rails 3.1嵌入了has_many:通过内置的关联。这是一个ASCIIcast

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

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

我不确定它是否支持通过多态asociations进行嵌套,但是可能值得查看来自README的nested_has_many_through插件:

...可以定义has_many :through其他has_many关系:through关系,可能通过任意深层次结构。 这允许构建跨越任意数量的表的关联,而不必求助于find_by_sql (如果您需要通过:include切换加载,这不是一个合适的解决方案)。

试试这个(Rails 3):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM