1

I have a list of items Obj:

obj1.val = ["foo"]
obj2.val = ["bar"]
obj3.val = ["bar", "foo"]

And I have an array check_list = ["foo","bar"]

I know that code like Obj.where('val @> ARRAY[?]', check_list) will return obj3 because it contains "foo" and "bar" but I want to create a function that will return all items.

I was thinking about some loop like: based on check_list.each but it just doesn't look good. How to make such a query?

1 Answer 1

6

Please use the && overlap operator.

Obj.where('val && ARRAY[?]', check_list)

Tried out example :

development=# select id, group_ids from users;
 id | group_ids
----+-----------
  1 | {1}
  2 | {1,2}
  3 | {2}
(3 rows)

[arup@sampl_admin (master)]$ rails c
Loading development environment (Rails 4.2.3)
>> User.where('group_ids && ARRAY[?]', [1, 2]).pluck(:id, :group_ids)
   (1.0ms)  SELECT "users"."id", "users"."group_ids" FROM "users" WHERE (group_ids && ARRAY[1,2])
# => [[1, [1]], [2, [1, 2]], [3, [2]]]
Sign up to request clarification or add additional context in comments.

Comments

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.