views:

148

answers:

1

I cant get rails to return combined ('AND') searches on associated join tables of an Object.

E.g. I have Books that are in Categories. Lets say: Book 1: is in category 5 and 8

But I cant get 'AND' to filter results using the join table? E.g ::->

Class Books has_and_belongs_to_many :categories, :join_table => "book_categories"

Book.find :all, :conditions => "book_categories.category_id = 5 AND book_categories.category_id = 8", :include => "categories" ... returns nil (why does it not return all books that are in both 5 & 8 ??)

However: 'OR' does work:

Book.find :all, :conditions => "book_categories.category_id = 5 OR book_categories.category_id = 8" ... returns all books in category 5 and 8

I must be missing something?

+2  A: 

The problem is at the SQL level. That condition runs on a link table row, and any individual link table row can never have a category_id of both 5 and 8. You really want separate link table rows to have these IDs.

Try looking into Rails' named_scope, specifically the part that allows filtering with a lambda (so you can take an argument). I've never tried it out myself, but if I had to implement what you're looking for, that's what I'd look in to.

zenazn
Yeah, you want a result if the category's id is 5 OR 8, because it can never be simultaneously 5 AND 8.
Jon Smock