Find record, that has ALL associated records

ⅰ亾dé卋堺 提交于 2019-12-01 21:20:34
mark
@people = Person.find(:all, 
   :joins => :favourites,
   :select => "person.*, count(favourites) favourite_count", 
   :conditions => {:favourites => @array_of_favourites}, 
   :group => "persons.id having favourite_count = #{@array_of_favourites.count}")

You'll need something like this to find people with all favourites rather than any combination of favourites. This is based on the assumption that you have an array of favourite objects, rather than a collection of strings.

Rails 4 compatible solution:

@people = Person.joins(:favourites)
  .where(favourites: { id: @array_of_favourites })
  .group("people.id")
  .having("count(favourites.id) = #{@array_of_favourites.count}")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!