我有一个很多属于食谱和配料协会。
我试图返回在给定的整数数组中包含所有成分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的配方?
试试这个查询:
# Ingredient ID array
ingredient_ids = [....]
Recipe.joins(:ingredients).where(ingredients: { id: ingredient_ids }).
group("recipes.id").
having('count(recipes.id) >= ?', ingredient_ids.size)
希望能帮助到你!