Yossale
Yossale

Reputation: 14361

ActiveRecord: search by array field element inside another array

I have an object with an array field, called emails

user.emails = ['[email protected]','[email protected]']

I want to find all the users from a list of emails:

emails_to_find = ['[email protected]','[email protected]']

I tried running

User.where(emails: emails_to_find)

but I get

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:  array value must start with "{" or dimension information

How do I do that? What the error means?

Upvotes: 1

Views: 236

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

If the column is of type Array and in the migration that created it you have something like t.string 'emails', array: true, try using:

User.where("emails @> ARRAY[?]::varchar[]", ['[email protected]','[email protected]'])
User.where("'[email protected]' = ANY (emails)")

Upvotes: 3

Related Questions