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
答案 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启发了解决方案。