【问题标题】:Make a Scope condition check if an Array has at least one element of another array做一个范围条件检查一个数组是否至少有另一个数组的一个元素
【发布时间】:2018-07-28 15:24:22
【问题描述】:

我正在尝试创建一个范围,以带回至少具有我在数组中作为参数发送的一种用途的所有建筑物。

我的建筑模型有一个列types_of_use,属性为array: true

如何创建一个范围来检查我发送的至少一个值是否在数组中并将结果保留为ActiveRecord_Relation

Building.first.types_of_use # Returns ["Offices", "Comercial"]

uses = ["Hotel", "Comercial"]

Building.with_uses(uses) # Should return the first building

【问题讨论】:

    标签: ruby-on-rails arrays ruby activerecord rails-activerecord


    【解决方案1】:

    如果这是 PostgreSQL,那么你会想要使用 && (overlaps) operator:

    &&
    重叠(有共同元素)
    ARRAY[1,4,3] && ARRAY[2,1]
    t

    您还需要使用array constructor syntax

    array[?]
    

    因为 ActiveRecord 喜欢将值是数组的占位符扩展为逗号分隔值的列表。

    综合起来,您的作用域可能如下所示:

    def self.with_uses(uses)
      where('buildings.types_of_use && array[?]', uses)
    end
    

    或者,如果您更喜欢使用scope 方法来定义范围:

    scope :with_uses, ->(uses) { where('buildings.types_of_use && array[?]', uses) }
    

    但是"Using a class method is the preferred way to accept arguments for scopes" 所以我通常对带参数的作用域使用显式类方法。

    【讨论】:

    • 这正是我要找的,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2017-03-03
    • 2021-01-30
    相关资源
    最近更新 更多