Ruby On Rails 5,activerecord查询,其中模型关联标识包括数组中的所有标识

编程入门 行业动态 更新时间:2024-10-28 20:21:10
本文介绍了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查询,其中模型关联标识包括数组中的所有标识

    本文发布于:2023-10-28 22:40:26,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1537980.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:标识   组中   模型   Ruby   Rails

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!