Rails查询,需要数组中的所有条件

时间:2022-07-18 00:13:49

I have two models, both associated with each other through has_many through.

我有两个模型,都通过has_many相互关联。

I can query the model and filter based on its associated records:

我可以查询模型并根据其相关记录进行过滤:

Car.includes(:equipment).where(equipment: { id: [1, 2, 3] })

Car.includes(:equipment).where(设备:{id:[1,2,3]})

The problem is that I want to require all of those records, rather than requiring just one of them.

问题是我想要所有这些记录,而不是只需要其中一个。

Is there a way to build a query that requires all of the values in the array (the [1, 2, 3] from the above example).

有没有办法构建一个需要数组中所有值的查询(上例中的[1,2,3])。

In other words, I'd like to query for all cars that have all three equipment (ids of 1, 2 and 3).

换句话说,我想查询所有拥有所有三种设备(ID为1,2和3)的汽车。

1 个解决方案

#1


1  

Assuming you have an id_ary like [1,2,3], how about something like:

假设你有一个类似[1,2,3]的id_ary,那么如下:

id_ary.each_with_object(Car.includes(:equipment)) do |id, scope|
  scope.where(equipment: {id: id})
end

Looping like that should and your where conditions, I believe.

我相信,这样的循环应该和你的条件相符。

#1


1  

Assuming you have an id_ary like [1,2,3], how about something like:

假设你有一个类似[1,2,3]的id_ary,那么如下:

id_ary.each_with_object(Car.includes(:equipment)) do |id, scope|
  scope.where(equipment: {id: id})
end

Looping like that should and your where conditions, I believe.

我相信,这样的循环应该和你的条件相符。