0

I am trying to write an activerecord query in my index action that only shows Trips that have a category type of "Beaches". Here is my code:

Trip.includes(:categories).where("categories.type" == "#{params[:activity]}").all

params[:activity] returns "Beaches".

That query is not doing what I Think is doing and seems to give me back all Trips. What am I doing wrong?

Albin
  • 2,912
  • 1
  • 21
  • 31
Jwan622
  • 11,015
  • 21
  • 88
  • 181

1 Answers1

1

When you do it like you wrote above the condition in the where clause is applied to the categories.

This means You fetch all Trips then to each of them you give them a list of categories where the type equals "Beaches".

What you want to be doing is something like:

Trip.joins(:categories).where(categories: { type: params[:activity]} )

You can read more on joins vs includes here Rails :include vs. :joins

Community
  • 1
  • 1
Albin
  • 2,912
  • 1
  • 21
  • 31