user1411469
user1411469

Reputation: 379

Rails: querying based on method not in database table

I have a Restaurant and Category class that both have a has_and_belong_to_many relationship. Through this association, I get a restaurant.category_ids method that returns an array.

I want to select the restaurants that belong to the specified categories (can be more than one). How do I build this query?

So far, I have:

@restaurants = Restaurant.joins(:categories).where('categories.id' =>    params[:category_ids])

But this returns duplicates as well as restaurants that fit just one of the categories.

For example, search for American, cheap, and fast food restaurants gives me ["Mcdonald's", "McDonald's", McDonald's", "Burger King"] for @restaurants.

I have also tried:

@restaurants = Restaurant.where(:category_ids => params[:category_ids])

But category_ids is not a database field, and this doesn't work.

Note: params[:category_ids] is an array of ids.

Thanks for any help!

Upvotes: 2

Views: 60

Answers (1)

Mike Szyndel
Mike Szyndel

Reputation: 10592

I think the only viable solution would be to generate the query like

Restaurant.joins(:categories).where('categories.id' => cat_id1).where('categories.id' => cat_id2)...

because then you will get first where AND second where AND...

To get records only once you need to add .distinct

So a whole solution would be like (I'm not sure if this is valid syntax)

query = Restaurant.joins(:categories)
category_ids.each do |category_id|
  query = query.where('categories.id' => category_id)
end
query.distinct

Upvotes: 1

Related Questions