2010-06-21 64 views
0

我有兩個型號:汽車圖片在我的回報率的項目查找父母沒有或在軌多態關聯孩子

class Car < ActiveRecord::Base 
    has_many :pictures, :as => :imageable, :dependent => :destroy 
end 

class Picture < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true, :dependent => :destroy 
end 

我怎樣才能找到所有隻有兒童圖片的汽車?

回答

2

我沒有測試過,但我認爲這樣的事情會令它在一個單一的查詢。

class Car < ActiveRecord::Base 
    has_many :pictures, :as => :imageable, :dependent => :destroy 
    named_scope :with_child_picture, lambda { { 
     :joins => :pictures, 
     :group => "pictures.imageable_id", 
     :conditions => ["pictures.imageable_id != ?", nil] 
    } } 
end 

而且你可以使用它作爲

Car.with_child_picture 

我無法測試它自己...但是我希望至少它給你的想法。

+0

感謝您的解決方案!它爲我工作。我只是修正了一個小表達式:conditions => [「pictures.imageable_id IS NOT NULL」] – 2010-06-21 16:24:39

0

這可能會變得混亂/緩慢,但一種選擇是遍歷所有的汽車,並檢查是否有多少個孩子排隊。

good_cars = [] 
Cars.all.each do |car| 
    if (car.pictures.count > 0 && car.pictures.count == Picture.find_by_car_id(car.id).count) 
    good_cars << car 
    end 
end 

或者,如果你想提高性能

good_cars = [] 
Cars.all.each do |car| 
if (car.pictures.count > 0) 
    pic_count_for_car = Picture.count_by_sql(
     "SELECT COUNT(*) from pictures WHERE car_id = #{car.id}" 
    ) 
    if (car.pictures.count == pic_count_for_car) 
     good_cars << car 
    end 
    end 
end 
+0

我在緊急情況下想到了這個解決方案。但是,無論如何,這也是有效的。 – 2010-06-21 16:26:33