Ruby On Rails 5,activerecord查询,其中模型关联标识包括数组中的所有标识 [英] Ruby On Rails 5, activerecord query where model association ids includes ALL ids in array
本文介绍了Ruby On Rails 5,activerecord查询,其中模型关联标识包括数组中的所有标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个食谱和配料协会。
I have a Has many belongs to association for Recipes and Ingredients.
我试图返回包含所有给定整数数组的配料ID的食谱。
例如我使用多种成分进行搜索,并且想要返回包含所有成分的任何食谱。如果配料太多,但是食谱包括了所有配料,那么它也应该返回食谱。
I am trying to return recipes which have all the ingredient ids in a given array of integers. Eg. I search using multiple ingredients, and I want to return any Recipe that has all the ingredients. If too many ingredients are given, but the Recipe includes them all, it should also return the recipe.
我尝试了几件事,
Recipe.joins(:ingredients).where(ingredients: { id: ids })
返回具有任何成分的食谱
which returns the Recipes that have ANY of the ingredients
Recipe.joins(:ingredients).where('ingredients.id LIKE ALL ( array[?])', ids)
这将导致错误:错误:运算符不存在:整数~~整数
我该如何
推荐答案
尝试此查询:
# Ingredient ID array
ingredient_ids = [....]
Recipe.joins(:ingredients).where(ingredients: { id: ingredient_ids }).
group("recipes.id").
having('count(recipes.id) >= ?', ingredient_ids.size)
- 第一行确保仅提取具有任何成分的食谱
- 第二个&第三行确保已加载的配方具有id数组的最小成分大小,因此,如果缺少任何成分,则不会考虑。
希望有帮助!
这篇关于Ruby On Rails 5,activerecord查询,其中模型关联标识包括数组中的所有标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文