【问题标题】:Rails/PSQL - turning a column table into an array and search if a subarray is includedRails / PSQL - 将列表转换为数组并搜索是否包含子数组
【发布时间】:2017-04-23 16:29:26
【问题描述】:

我完全被这个问题困住了,我找不到任何关于我的疑问的答案。

我会尽量用最好的方式解释,但这很难。

所以,我有了第一个模型(配方),它在列成分中存储了数组中的所有成分。我还有一个成分模型,它通过一个连接表连接到配方,第一列是所有可用成分的名称。

我想在我的搜索方法中包含一个查询,该查询将 components.name 列转换为一个数组,并从搜索方法只返回那些成分数组完全包含在 ingredients.name 数组中的食谱。

我试过这个

recipes = recipes.joins(:ingrediantizations).where('array_agg('ingredients.name') @> recipe.ingredients')

但它没有给出正确的结果 - 成分是连接表。

希望你能帮帮我!

【问题讨论】:

    标签: ruby-on-rails arrays postgresql


    【解决方案1】:

    经过几天的思考,我终于找到了解决方案。

    我发布它是为了有人可以从中受益。

    第二步可能看起来很奇怪,但我猜,它是使用大括号创建数组的唯一方法,这是 PSQL 中文字数组的要求。

    Ingredients 是将成分存储在数组中的属性。

     items = Item.pluck(:name)
        items = "{#{ items.map {|term| %Q("#{ term }") }.join(",") }}"
        recipes=recipes.where("ingredients <@?", "#{items}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2023-02-04
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      相关资源
      最近更新 更多