问题描述
(使用 in
子句按字段对选择查询)
(Select Query by Pair of fields using an in
clause)
我有一个看起来像这样的哈希数组:
I have an array of hashes that looks like this:
[ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]
我想返回的是 Items
表中匹配数组中字段对的所有记录.
What I would like to return are all the records in the Items
table that match the pair of fields in the array.
在 SQL 中,它会像这样检索:
In SQL it would be retrieved like this:
SELECT *
FROM items
WHERE (product_id, group_id) IN (VALUES (7629,4), (8202,3))
但是我在使用 rails .where
子句时遇到了麻烦.这甚至可能吗?
But I am having trouble doing this with a rails .where
clause. Is this even possible?
推荐答案
我认为在这种情况下使用 SQL 的 IN
没有任何好处.
I see no benefit in using SQL's IN
in this case.
我会使用 where
作为第一个条件,并使用 or
(并让 Rails 负责消毒和繁重的工作):
I would use where
for the first condition and chain all other conditions with or
(and let Rails take care of sanitizing and heavy lifting):
array = [{ product_id: 7629, group_id: 4 }, { product_id: 8202, group_id: 3 }]
array[1..-1].inject(Model.where(array[0])) { |m, h| m.or(Model.where(h)) }
这篇关于Rails 使用散列数组查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!