Ruby On Rails 5,activerecord query其中模型关联id包括数组中的所有id

问题描述 投票:4回答:1

我有一个很多属于食谱和配料协会。

我试图返回在给定的整数数组中包含所有成分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的配方?

ruby-on-rails ruby activerecord
1个回答
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数组的最小成分大小,因此如果缺少任何成分,则不会考虑它。

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.