AntonAL
AntonAL

Reputation: 17430

Find record, that has ALL associated records

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 ?

Upvotes: 3

Views: 1016

Answers (1)

mark
mark

Reputation: 10574

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

Upvotes: 5

Related Questions