Cesar Cesar - 1 month ago 9
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

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)
Comments