2009-07-03 29 views
1

我希望這將是重塑這種自定義查詢一個容易:)我已經餡兜了幾個小時用的has_many選項試圖仿效玩這個:使用的has_many

has_many :pages, :finder_sql => %q(SELECT * FROM `pages` LEFT OUTER JOIN `component_instances` ON `component_instances`.instance_id = `pages`.id AND `component_instances`.instance_type = 'Page' WHERE `component_instances`.parent_id = #{id}) 

這基本上是一個多態加入,所以有component_instances表作爲中央結構,並有不同類型的東西掛起來。這是一個嵌套集合(在這種情況下不重要)。

問題似乎是,has_many不允許我操縱連接條件。我無法取消自動生成的外鍵加入條件。

上面的代碼有效,但我想對結果使用範圍,而這對於自定義查詢是不可能的。

任何幫助,將不勝感激:)

乾杯,

布蘭頓

回答

0

大聲笑,睡在它給我的答案是:

class PageSet < ActiveRecord::Base 

    unloadable 

    set_table_name "component_instances" 

    has_many :children, :foreign_key => :parent_id, :class_name => 'PageSet' 
    belongs_to :instance, :polymorphic => true, :dependent => :destroy 
    has_many :pages, :through => :children, :source => :instance, :source_type => 'Page' 

end 

通過PARENT_ID鏈接的實體是正確的孩子,我是隻是以錯誤的方式提及它們,但是AR沒有提出任何錯誤:)

0

你可以做到這一點與:通過選項。

has_many :pages, :through => :component_instances, :source => :parent, :source_type => 'Page' 
0

感謝鉛邁克爾,到底這工作:

has_one :page_set, :foreign_key => :parent_id 
    belongs_to :instance, :polymorphic => true, :dependent => :destroy 
    has_many :pages, :through => :page_set, :source => :instance, :source_type => 'Page', :extend => LearningCaveFilterExtension 

,但它是一個有點粗略爲:page_set方法實際上返回的東西完全錯誤的。理想情況下,它應該返回自我,但我需要把parent_id作爲外鍵,以便從has_many頁面聲明中生成的SQL是正確的(使用:id將是正確的方式,但是然後擰緊:pages方法。頭腦還沒有完全得到這裏發生的事情,但至少它的工作原理和範圍的作品也:)

感謝您的幫助,如果你有任何解釋爲什麼這樣的作品,請讓我知道:)