【问题标题】:Rails where clause when something is stored as array当某些东西存储为数组时,Rails where 子句
【发布时间】:2016-06-23 22:55:58
【问题描述】:

我正在运行带有 PG 数据库的 rails 4.2。

我有一个项目存储在数据库中,例如(模型Item):

:something => ["1", "2", "3"]

我想得到Item.where(:something.include? => "3")

显然这是行不通的 - 但你打算如何在 Rails 中执行此操作?

【问题讨论】:

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


    【解决方案1】:

    根据documentation,这样的事情应该可以工作:

    Item.where('something @> ARRAY[?]::varchar[]', ['3'])
    

    【讨论】:

    • 根据文档,当我们只查找一个元素时,可以使用一种更短的方法。 Item.where("'3' = ANY (something)") 我很震惊,没有更简单的 activerecord 方法来做到这一点!
    • @MaxChrétien:我(或您)可以在答案中包含您的评论吗?我认为它可以被认为是非常有用的。
    • 评论被拒绝。 此编辑旨在解决帖子的作者,作为编辑毫无意义。它应该写成评论或答案。
    【解决方案2】:

    除了@potashin 回答之外,如果您需要在 one 元素上获取项目,还有一种更短的方法(请参阅documentation)。

    # Items for a single something
      Item.where("'3' = ANY (something)")
      # Or using '?'
      Item.where('? = ANY (something)', '3')
    
    # Items for multiple something
      Item.where('something @> ARRAY[?]::varchar[]', ['3', '4'])
    

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2014-05-12
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多