What’s the best way to do IS IN queries, especially when involving a join?
Currently, I have something like the following:
Table1.joins(:table2).where( { :table2s => { :ident => params[:idents].split(',') } } )
This works and gets the job done. The resulting WHERE clause is something like
WHERE "table2s"."ident" IS IN ('a','b','c')
I feel like this would be cleaner though:
Table1.joins(:table2).where("table2s.ident IS IN ?", params[:idents]:split(','))
Is there a way to avoid the first style and use something more like the second style? (i.e., the where method recognizes the array and uses IS IN rather than ‘=’ operator)
Letting the query compiler do it for you is generally a better way to do it as it will handle cases you might forget, such as passing a
nilvalue and ending up with an erroneousIS IN(NULL)instead ofIS NULL. You can clean up your statement, though:Taking this a step further, you can reduce it to:
You could further clean this up by writing a scope that encapsulates this instead of using this as-is.