查找具有与列表中的所有条目匹配的子记录的记录

时间:2009-09-30 02:26:25

标签: ruby-on-rails

def DogOwner < ActiveRecord::Base
  has_many :dogs
  has_many :breeds, :through => dogs

  def self.with_breeds(breeds)
    # returns a list of DogOwner records who own all breeds in the list

    # ex: DogOwner.with_breeds("Dalmation","Poodle")
    # or it could be DogOwner.with_breed_ids(1,3) which would only require
    # a join down to the dogs table - I could live with that.

    # do i need to hand generate SQL with n levels of subselects?
    # or is there something in ActiveRecord that handles this magically?
  end
end

1 个答案:

答案 0 :(得分:2)

我想出了一种使用子ID列表的方法:

DogOwner.all(:joins => :dogs, 
             :conditions => "dogs.breed_id in (#{list_of_breeds})", 
             :group => 'dog_owners.id', 
             :having => "count(*) = #{list_of_breeds.size}")

信用:Ethan Vizitei's Blog Post启发了解决方案。

相关问题