我想不出任何方法來做到這一點,而不訴諸於SQL,即使與Arel。
由於數組不能被引用,我們必須做一些愚蠢的事情,仍然允許它被消毒。這不是一個偉大的解決方案,但它是一個工作。
your_hashes = [ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]
# turn hashes into simple value array
conditions = your_hashes.map { |h| [ h[:product_id], h[:group_id] ] }
=> [[7629, 4], [8202, 3]]
# create a list of "(?)" values that will allow the conditions to be passed in
values = ("(?)," * conditions.length)[0..-2]
=> "(?),(?)"
# use it to look up the values
Model.where("(product_id, group_id) IN (VALUES #{values})", *conditions)
# this is the generated sql:
SELECT "models".* FROM "models" WHERE ((product_id, group_id) IN (VALUES (7629,4),(8202,3)))
不錯!這比我提出的要好得多。然而,它正在用'array.shift'修改'array',我認爲這不是理想的。 (array.first)){| m,h | m.or(Model.where(h))}''會做同樣的事情而不改變數組。 – brainbag
更新了我的答案以解決該問題。 – spickermann