2012-12-05 44 views
2

我正在使用兩個不同模型的多態關聯標記模型。太棒了,容易。但是,這兩種模式中的一種也屬於另一種模式。ActiveRecord將兩個關係命名爲範圍到一個模型

class Facility < ActiveRecord::Base 
    has_many :units 
    has_many :taggings, :as => :taggable 
    has_many :tags, :through => :taggings 
end 
class Unit < ActiveRecord::Base 
    belongs_to :facility 
    has_many :taggings, :as => :taggable 
    has_many :tags, :through => :taggings 
end 
class Tagging < ActiveRecord::Base 
    belongs_to :taggable, :polymorphic => true 
    belongs_to :tag 
end 
class Tag < ActiveRecord::Base 
    has_many :taggings 
end 

我想寫一個範圍檢索所有單位一定標籤,包括屬於與標籤的基金的單位。這是行不通的:

named_scope :by_tag_id, lambda {|tag_id| 
{ 
    :select => "DISTINCT units.*", 
    :joins => [:taggings, {:facility => :taggings}], 
    :conditions => ["taggings.tag_id = ? OR taggings_facilities.tag_id = ?", 
    tag_id.to_i, tag_id.to_i] 
}} 

對於那個named_scope,我只能得到那些有標籤的單位。

有什麼想法?我在這裏錯過了很明顯的東西嗎

更新

我,不幸的是,on Rails的2.3.x版本,1.8.7紅寶石。

我現在正在嘗試一些更明確地寫入連接的技術。

更新2

我不能回答我的問題,因爲我沒有信譽。哎呀。我真的應該貢獻更多...

嗯,我想我只是需要捅一下,再推一點。下面是我的工作:

named_scope :by_tag_id, lambda {|tag_id| 
    { 
    :select => "DISTINCT units.*", 
    :joins => [ 
     "INNER JOIN facilities as bti_facilities ON units.facility_id = bti_facilities.id", 
     "LEFT JOIN taggings AS bti_facilities_taggings 
      ON bti_facilities_taggings.taggable_id = bti_facilities.id AND bti_facilities_taggings.taggable_type = 'Facility'", 
     "LEFT JOIN taggings AS bti_units_taggings ON bti_units_taggings.taggable_id = units.id AND bti_units_taggings.taggable_type = 'Unit'", 
     ], 
    :conditions => ["bti_units_taggings.tag_id = ? OR bti_facilities_taggings.tag_id = ?", tag_id.to_i, tag_id.to_i] 
    } 
} 

我使用一些模糊故意表的別名,以儘量避免與其他命名範圍衝突。 (我沒有設施別名開始,我遇到了查詢的SQL錯誤,我試圖鏈接到另一個範圍,引用設施表)。

如果有人有更好的答案或對我的一些反饋方法,我會聽到它。

回答

0

我看到您已經回答了您的問題,但如果您在原始查詢中使用:include =>而不是:join =>,則會生成LEFT OUTER JOIN。也就是說,您可能不需要加載關聯,只需查詢關聯,因此您的里程可能會有所不同。

+0

謝謝你,我以爲我用':include =>'方法嘗試了(並失敗了),但顯然我已經破壞了方法的其他組件。 –

+0

This works: 'named_scope:by_tag_id,lambda {| tag_id | :select =>「DISTINCT units。*」, :include => [:taggings,{:facility =>:taggings}], :conditions => [「taggings.tag_id =?OR taggings_facilities.tag_id = ?「,tag_id.to_i,tag_id.to_i] } }' –

0

我想知道你是否可以寫這樣的東西?

named_scope :by_tag_id, lambda {|tag_id| 
    { 
    :select  => "DISTINCT units.*", 
    :include => [:tags, {:facility => :taggings}], 
    :conditions => { :tags => { :tag_id => tag_id } } 
    } 
} 
相關問題