Rails join ('AND') on linked join tables

I am unable to get rails to return combined ('AND') queries on related object join tables.

eg. I have Books that are in Categories. Let's say: Book 1: is in category 5 and 8

But I can't get 'AND' to filter the results using join table? For example: →

Has_and_belongs_to_many: categories ,: join_table => "book_categories" class books

Book.find: all ,: conditions => "book_categories.category_id = 5 AND book_categories.category_id = 8" ,: include => "categories" ... returns zero (why doesn't it return all books that are in 5 and 8 ?)

However: "OR" works:

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

Am I missing something?

+1


a source to share


1 answer


The problem is at the SQL level. This condition is met in the link table row, and any single row row row can never have category_id

both 5 and 8. You really want the individual link table rows to have these IDs.



Try looking in Rails named_scope

, specifically the part that lets you filter with a lambda (so you can take an argument). I've never tried this myself, but if I had to implement what you're looking for, that's what I would look at.

+2


a source







All Articles