检查attr数组是否包含Rails中给定数组的任何元素 [英] Check if attr array contains any of element from given array in Rails
本文介绍了检查attr数组是否包含Rails中给定数组的任何元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目Obj列表:
I have a list of items Obj:
obj1.val = ["foo"]
obj2.val = ["bar"]
obj3.val = ["bar", "foo"]
我有一个数组 check_list = [ foo, bar]
我知道像 Obj.where('val @> ARRAY [?]',check_list)
这样的代码将返回 obj3
,因为它包含 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.
我在考虑类似这样的循环:基于 check_list.each
,但看起来并不好。
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?
推荐答案
请使用 &&
重叠运算符。
Please use the &&
overlap operator.
Obj.where('val && ARRAY[?]', check_list)
试用示例:
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]]]
这篇关于检查attr数组是否包含Rails中给定数组的任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文