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

Rob*_*hes 5 ruby activerecord ruby-on-rails

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

我正在尝试返回在给定的整数数组中具有所有成分ID的配方。例如。我使用多种成分进行搜索,并且想要返回包含所有成分的任何食谱。如果给出的成分太多,但是食谱包括了所有成分,那么它也应该返回食谱。

我已经尝试了几件事,

Recipe.joins(:ingredients).where(ingredients: { id: ids })
Run Code Online (Sandbox Code Playgroud)

返回包含任何成分的食谱

Recipe.joins(:ingredients).where('ingredients.id LIKE ALL ( array[?])', ids)
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误: ERROR: operator does not exist: integer ~~ integer

我怎样才能只找到包含数组中所有ID的配方?

Ash*_*man 2

尝试这个查询:

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

Recipe.joins(:ingredients).where(ingredients: { id: ingredient_ids }).
  group("recipes.id").
  having('count(recipes.id) >= ?', ingredient_ids.size)
Run Code Online (Sandbox Code Playgroud)
  1. 第一行确保只获取包含任何成分的食谱
  2. 第二行和第三行确保加载的食谱具有 id 数组的最小成分大小,因此如果缺少任何成分,则不会考虑它。

希望能帮助到你!