从数组中查找包含属性组合的所有记录

Find all records that contain a combination of attributes from an array

我有一个名为 LayerProducts 的 table,它包含 layer_idproduct_id 属性。

我想创建一个查询,我可以在其中传递一个数组,如下所示:

[ [:layer1_id, :product1_id], [:layer2_id, :product2_id], [:layer3_id, :product3_id] ]

和 return LayerProduct 中包含所提供的任何组合的所有记录。

父数组不是固定长度的,因此查询需要是动态的以容纳任意数量的组合。

这可能吗?如果可以,我将如何使用 SQL 或活动记录创建此查询?

您可以构造原始 sql 并使用活动记录。 像这样:

def self.for_multiple_lp(arr=[])
  # Handle case when arr is not in the expected format.
  condition = arr.collect{|a| "(layer_id = #{a[0]} AND product_id = #{a[1]})"}.join(" OR ")
  where(condition)
end

对于没有 activerecord 的原始 sql 你可以参考 this