I need to check my records against multiple like statements, what is the best way to do so? i.e.
names = ['alice', 'bob', 'mark']
I've got table lets say People in my database or (Peoples) so I want to select all people who have names such as those 3 above.
found this answer :
https://stackoverflow.com/a/5333281/169277
For using like but I couldn't figure out how to pass array of values instead of single values. any ideas?
UPDATE :
I need like because people have two names
There are a number of plugins to that provide for this kind of query, but all you really need is Arel.
You'll need to prepare the query parameters for LIKE using something like this
wildcard_names = names.collect { |name| "%#{name}%" } # => ["%alice%","%bob%","%mark%"]
Then you'd used the #matches_any method of Arel.
people_table = People.arel_table
People.where(people_table[:name].matches_any(wildcard_names))
As PriteshJ mentioned, add to_sql to confirm the query is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With