Ruby On Rails 5, activerecord query where model association ids includes ALL ids in array

不问归期 提交于 2019-12-21 16:45:10

问题


I have a Has many belongs to association for Recipes and Ingredients.

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.

I have tried a few things,

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)

This gives an error: ERROR: operator does not exist: integer ~~ integer

How can I find only the recipes that include all of the ids given in the array?


回答1:


Try this query:

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

Recipe.joins(:ingredients).where(ingredients: { id: ingredient_ids }).
  group("recipes.id").
  having('count(recipes.id) >= ?', ingredient_ids.size)
  1. First line ensure that only recipes having any of the ingredients are fetched
  2. Second & third lines ensure that loaded recipes have minimum ingredient size of the id array, so that if any of the ingredient is missing it won't be considered.

Hope it helps!



来源:https://stackoverflow.com/questions/48990859/ruby-on-rails-5-activerecord-query-where-model-association-ids-includes-all-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!