【问题标题】:Ruby On Rails 5, activerecord query where model association ids includes ALL ids in arrayRuby On Rails 5,模型关联 id 包括数组中的所有 id 的 activerecord 查询
【发布时间】:2018-02-26 14:33:52
【问题描述】:

我有很多属于食谱和成分的关联。

我正在尝试返回在给定整数数组中包含所有成分 ID 的食谱。 例如。我使用多种成分进行搜索,并且我想返回包含所有成分的任何食谱。如果提供的成分太多,但配方包含所有成分,它也应该返回配方。

我已经尝试了一些东西,

Recipe.joins(:ingredients).where(ingredients: { id: ids })

返回包含任何成分的食谱

Recipe.joins(:ingredients).where('ingredients.id LIKE ALL ( array[?])', ids)

这给出了一个错误:ERROR: operator does not exist: integer ~~ integer

如何仅找到包含数组中给定的所有 id 的食谱?

【问题讨论】:

  • 未对此进行测试:Recipe.joins(:ingredients).where(ingredients: { id: ids }).group_by('recipes.id').having('COUNT(*) = ?', ids.size)。如果可行,我将创建一个答案:)
  • 嗨,这给出了一个错误·错误数量的参数(给定 1,预期为 0)·这也不适用于我的预期目的(我会让问题更清楚)。如果搜索数组的成分比食谱多,它也应该返回食谱,但如果缺少一种成分,它不应该。
  • Recipe.joins(:ingredients).where(ingredients: { id: ids }).group_by('recipes.id').having("COUNT(*) = #{ids.size}") ?
  • 同样的错误:参数数量错误(给定 1,预期为 0)

标签: ruby-on-rails ruby activerecord


【解决方案1】:

试试这个查询:

# Ingredient ID array
ingredient_ids = [....]

Recipe.joins(:ingredients).where(ingredients: { id: ingredient_ids }).
  group("recipes.id").
  having('count(recipes.id) >= ?', ingredient_ids.size)
  1. 第一行确保只获取包含任何成分的食谱
  2. 第二行和第三行确保加载的食谱具有 id 数组的最小成分大小,因此如果缺少任何成分,则不会考虑它。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多