I need to make a where query from an array where each member of the array is a ‘like’ operation that is ANDed. Example:
SELECT ... WHERE property like '%something%' AND property like '%somethingelse%' AND ...
It’s easy enough to do using the ActiveRecord where function but I’m unsure how to sanitize it first. I obviously can’t just create a string and stuff it in the where function, but there doesn’t seem to be a way possible using the ?.
Thanks
The easiest way to build your LIKE patterns is string interpolation:
and if you have all your strings in an array then you can use ActiveRecord’s query chaining and
injectto build your final query:Then you can
q.allorq.limit(11)or whatever you need to do to get your final result.Here’s a quick tutorial on how this works; you should review the Active Record Query Interface Guide and the
Enumerabledocumentation as well.If you had two things (
aandb) to match, you could do this:The
wheremethod returns an object that supports all the usual query methods so you can chain calls asM.where(...).where(...)...as needed; the other query methods (such asorder,limit, …) return the same sort of object so you can chain those as well:You have an array of things to LIKE against and you want to apply
whereto the model class, then applywhereto what that returns, then again until you’ve used up your array. Thing that look like a feedback loop tend to call forinject(AKAreducefrom “map-reduce” fame):So
injecttakes the block’s output (which is the return value ofwherein our case) and feeds that as an input to the next execution of the block. If you have an array and youinjecton it:then that’s the same as this:
Or, in pseudocode: