Rails: querying based on method not in database table -


i have restaurant , category class both have has_and_belong_to_many relationship. through association, restaurant.category_ids method returns array.

i want select restaurants belong specified categories (can more one). how build query?

so far, have:

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

but returns duplicates restaurants fit 1 of categories.

for example, search american, cheap, , fast food restaurants gives me ["mcdonald's", "mcdonald's", mcdonald's", "burger king"] @restaurants.

i have tried:

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

but category_ids not database field, , doesn't work.

note: params[:category_ids] array of ids.

thanks help!

i think viable solution generate query like

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

because first , second and...

to records once need add .distinct

so whole solution (i'm not sure if valid syntax)

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

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -