Cesar Cesar - 2 years ago 125
Ruby Question

Rails filtering by a has_and_belongs_to_many attribute

I have a bit of a problem! I have a Place model and a Category model which are connected through has_and_belongs_to_many. I wish to be able to filter out all places which belong to atleast one of the categories in a given array (int array of ids). So far I've only been able to filter by a single category with the following code:

@places = Place.find(:all, :include => :categories, :conditions => { "categories_places.category_id" => id})

so basically instead of id I want ids. I hope there are some rails experts here who can help! I'm very new to this.

Answer Source

This should do the trick nicely.

some_array_of_ids = [1, 2, 3]
@places = Place.find(:all, :include => :categories, :conditions => ['categories.id IN (?)', some_array_of_ids)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download