5

So let's say i have a Customer model with array column phones. It's pretty easy to find all customers with given phone

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

But i can't figure out how to use LIKE with wildcard when i want to find customers with phones similar to given one, something like:

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

I'm using PostgreSQL 9.5 and Rais 4.2

Any ideas?

6
  • What database are you using? Commented Oct 19, 2016 at 12:05
  • @CdotStrifeVII he is using postgres. check tags. Commented Oct 19, 2016 at 12:09
  • @CdotStrifeVII Postgresql. I wrote it in tags but forgot to mention in post. Commented Oct 19, 2016 at 12:09
  • ANY is to be used for array comparison (postgresql.org/docs/9.4/static/functions-comparisons.html). What are you trying to do? Find costumer who have a phone number in that pattern? Commented Oct 19, 2016 at 12:26
  • @lcguida exactly. Commented Oct 19, 2016 at 12:50

2 Answers 2

2

I think, first of all, its better to use second table phones with fields customer_id, phone_number. I think it's more rails way ). In this way you can use this query

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

If you serialize your array in some text field, by example JSON, you should use % on both sides of your pattern:

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

If you have an array in your database, you should use unnest() function to expand an array to a set of rows.

Sign up to request clarification or add additional context in comments.

Comments

1

Can you try this

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

I believe this will work.

1 Comment

'%+7985%' will be the correct way, i believe. For cases like ['+7921123456', '+7985123456']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.