簡體   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