在rails中找到没有或有子女的多态关联的父母

时间:2010-06-21 13:28:04

标签: ruby-on-rails ruby polymorphic-associations

我的RoR项目中有两个模型:汽车图片

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 个答案:

答案 0 :(得分: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

我自己无法测试......但我希望至少它能给你一个想法。

答案 1 :(得分: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