Ruby on Rails - 选择数组中所有 id 的位置

Rob*_*hes 6 ruby arrays postgresql select ruby-on-rails

我试图找到最干净的方法来根据其关联和搜索数组选择记录。

我有Recipes其中有许多Ingredients(通过一个连接表),我有一个搜索表单域为arrayIngredient.ids

要查找包含搜索数组中任何 id 的任何配方,我可以使用

例如 1。

filtered_meals = Recipe.includes(:ingredients).where("ingredients.id" => ids)

但是,我只想匹配在搜索数组中找到所有成分的食谱。

例如2。

search_array = [1, 2, 3, 4, 5]
Recipe1 = [1, 4, 5, 6]
Recipe2 = [1, 3, 4]
# results => Recipe2
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用each循环,就像这样;

例如 3。

filtered_meals = []

 Recipes.each do |meal|
   meal_array = meal.ingredients.ids
   variable =  meal_array-search_array
     if variable.empty?
       filtered_meals.push(meal)
     end
   end
 end

 return filtered_meals
Run Code Online (Sandbox Code Playgroud)

这里的问题是分页。在第一个示例中,我可以使用.limit().offset()控制显示的结果数量,但在第三个示例中,我需要添加一个额外的计数器,将其与结果一起提交,然后在页面更改时,重新发送计数器并使用.drop(counter)each.do循环上。

这似乎太啰嗦了,有没有更好的方法来做到这一点?

jon*_*467 0

Ruby on Rails 指南 2.3.3 - 子集条件

Recipe.all(:ingredients => { :id => search_array })

应该导致:

SELECT * FROM recipes WHERE (recipes.ingredients IN (1,2,3,4,5))

在 SQL 中。