Find record, that has ALL associated records

一笑奈何 提交于 2019-12-20 02:49:07

问题


Say,

we have a "Person" and "Favorite" models.

"Favorite" is what this person likes: "music", "video", "sport", "internet", "traveling" etc.

"Person" HABTM "Favorites", and "Favorite" HABTM "Persons"

I need to find a Person, that has ALL listed "Favorites. For example, find a person, that likes "music", "traveling" and "sport".

How it can be done, using ActiveRecord.find method ?


回答1:


@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}")


来源:https://stackoverflow.com/questions/3416451/find-record-that-has-all-associated-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!