Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中查找无子级或有子级的多态关联的父级_Ruby On Rails_Ruby_Polymorphic Associations - Fatal编程技术网

Ruby on rails 在rails中查找无子级或有子级的多态关联的父级

Ruby on rails 在rails中查找无子级或有子级的多态关联的父级,ruby-on-rails,ruby,polymorphic-associations,Ruby On Rails,Ruby,Polymorphic Associations,我的RoR项目中有两个模型:汽车和图片 class Car < ActiveRecord::Base has_many :pictures, :as => :imageable, :dependent => :destroy end 及 我如何才能找到所有只有儿童图片的汽车?这可能会变得混乱/缓慢,但一个选择是迭代所有汽车,并检查是否有儿童排队 good_cars = [] Cars.all.each do |car| if (car.pictures.count &

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

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


我如何才能找到所有只有儿童图片的汽车?

这可能会变得混乱/缓慢,但一个选择是迭代所有汽车,并检查是否有儿童排队

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

我还没有测试过它,但我认为类似的东西可以在单个查询中实现

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

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

谢谢你提供了很好的解决方案!这对我有用。我刚刚修正了一个小表达式:conditions=>[pictures.imageable_id不是NULL]我在紧急情况下考虑过这个解决方案。不过还是要谢谢你,这也行。
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