【问题标题】:Check if attr array contains any of element from given array in Rails检查 attr 数组是否包含 Rails 中给定数组中的任何元素
【发布时间】:2015-08-23 10:36:14
【问题描述】:

我有一个项目 Obj 的列表:

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

我有一个数组check_list = ["foo","bar"]

我知道像Obj.where('val @> ARRAY[?]', check_list) 这样的代码会返回obj3,因为它包含“foo”和“bar”,但我想创建一个返回所有项目的函数。

我正在考虑一些循环,例如:基于check_list.each,但它看起来不太好。如何进行这样的查询?

【问题讨论】:

    标签: ruby-on-rails arrays postgresql


    【解决方案1】:

    请使用&& 重叠运算符。

    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]]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 2017-11-24
      • 2023-03-08
      相关资源
      最近更新 更多