问题
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