[英]Dynamically appending .or() calls to an active record query based on array elements
I have a function which runs a Conditional where query using a hash in order to chain conditions with an AND also. 我有一个函数,该函数运行条件查询,该查询使用哈希值进行查询,以便使用AND链接条件。
hash = {:cond1 => 6, :cond2 => 3, :cond3 => 7}
Object.where(hash)
This seems to work fine for me. 这对我来说似乎很好。
The problem is ,if I had an array of those hashes for example: 问题是,如果我有这些哈希的数组,例如:
ary = [{:cond1 => 6, :cond2 => 3, :cond3 => 7},{:cond4 => 6, :cond5 => 3, :cond6 => 7},....]
How could I dynamically chain every hash after ary[0] as an OR clause to a where query like so: 我如何将ary [0]之后的每个哈希作为OR子句动态链接到where查询,如下所示:
Object.where(ary[0]).or(ary[1]).or(ary[2])....
I think I may have to use lambdas or a block but I'm not sure how to implement it. 我想我可能必须使用lambda或代码块,但是我不确定如何实现它。
You can use inject to build your query: 您可以使用注入来构建查询:
ary[1..-1].inject(Object.where(ary[0]), :or)
This form takes all the elements but the first one, and for each they append .or(ary[i])
to the result, where the initial value is Object.where(ary[0])
. 这种形式采用除第一个元素外的所有元素,并为每个元素将
.or(ary[i])
附加到结果中,其中初始值为Object.where(ary[0])
。
Another way of doing the same thing is using a block: 做同一件事的另一种方法是使用块:
ary[1..-1].inject(Object.where(ary[0])) { |query, cond| query.or(cond) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.