Rob Mason
Rob Mason

Reputation: 79

How to search an array column for multiple strings

I have a column set up like this in my table

add_column :logs, :names, :string, array: true
add_index :logs, :names, using: :gin

I have this query to search the table via the names column to return records that contain robert

Logs.where("? = ANY (names)", 'robert')

I am curious on how to search the table for multiple names. Something like this, but the below query does not work

Logs.where("? = ANY (names)", ['robert', 'bob'])

I want it to function to something similar like this, where I pass in an array and returns all records that match

User.where(id: [1,2,3,4])

I need it as an OR statement

Upvotes: 2

Views: 1661

Answers (2)

Rajkumar P
Rajkumar P

Reputation: 179

User.where(names: ['robert', 'bob'])

User.where("names IN (?) ", ['robert', 'bob'])

note: Its case sensitive

This answer will also helps you

Upvotes: 1

7urkm3n
7urkm3n

Reputation: 6311

# SQL Contains Operator
1) User.where("names @> ARRAY[?]::varchar[]", ['robert', 'bob'])


# Contains Operator
2) User.where.contains(names: ['robert', 'bob'])


# Overlap Operator
3) User.where.overlap(names: ['robert', 'bob'])

Upvotes: 1

Related Questions