2010-06-21 52 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