views:

36

answers:

1

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  A: 
@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.

mark
Thanks. Good solution
AntonAL