Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where LIKE and array

How can I do something like this?

myarray = ["name1","name2"]
Product.where('name ILIKE ?', %#{myarray}%)

I need to get all products where names are like name1 and name2.

Is this possible?

like image 399
Martin Avatar asked Oct 16 '13 19:10

Martin


2 Answers

I think You want to test all values with ILIKE function.

This is how it's done in Postgres:

select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);

Try to convert to Rails/Ruby syntax like this:

myarray_with_percetage_signs = ["name1","name2"].map {|val| "%#{val}%" }
Product.where("name ILIKE ANY ( array[?] )", myarray_with_percetage_signs)
like image 163
Edgars Jekabsons Avatar answered Oct 16 '22 13:10

Edgars Jekabsons


Recently encountered the same issue, and, since neither answer helped me (I'm using a MySQL database), I thought I would share my solutions.

  • If you have a small database and don't mind retrieving all products, you could do the filtering after retrieving all products from the database using the following:

    Product.select { |product| myarray.any? { |str| product.name.include? str } }
    
  • If, however, you prefer to perform the query at the database level, you could use the WHERE REGEXP clause by converting the array to a pipe-separated list first:

    Product.where("`name` REGEXP '#{Regexp.new(myarray.join('|'))}'")
    
like image 1
Vadim Avatar answered Oct 16 '22 13:10

Vadim