Activerecord query on an array column using a template

So let's say I have a Customer model with a column in the phones array. It is quite easy to find all customers with this phone.

 Customer.where('? = ANY(phones)', '+79851234567') 

But I can't figure out how to use LIKE with a wildcard when I want to find clients with phones like this, for example:

 Customer.where('ANY(phones) LIKE ?', '+7985%') 

I am using PostgreSQL 9.5 and Rais 4.2

Any ideas?

+5
source share
2 answers

Can you try this

 Customer.where("array_to_string(phones, ', ') like ?", '+7985%') 

I think this will work.

+1
source

I think, first of all, it is better to use a second desk phone from the customer_id, phone_number field. I think this is more rails). So you can use this query

 Phone.where("phone_number LIKE ?", '%PART%').first.customer 

If you serialize your array in some text field, such as JSON, you should use% on both sides of your template:

 Customer.where('phones LIKE ?', '%+7985%') 

If you have an array in your database, you should use the unsest () function to expand the array to a rowset.

+2
source

Source: https://habr.com/ru/post/1258467/


All Articles