ActiveRecord / Psql - How to find records where column is like and item in an array

Viewed 11

I know you can search a column that contains any item in an array, like:

  arr = ["Seattle", "New York"]
    
  Company.where("location IN (?)", arr)

Now how do you search a column that is 'like' any item in an array?

Similar to:

 Company.where("location like '%Seattle%'")

But for each item in the array.

Thanks.

1 Answers

You can concatenate your array elements into a single string.

  • pro: extremely easy solution
  • con: if one string ends with foo and the next starts with bar and you search for foobar, then it will be a match

Conclusion: If you choose this approach, then for safety measure it would be helpful to use some separator.

You can use the similar to criteria:

lower(location) similar to '%(foo|bar|baz)%'

or you can create a table with keywords (if there are too many) and use a like criteria around the dynamic column name.

Related