Arel:如何使用 OR 干净地连接多个条件? [英] Arel: How to cleanly join multiple conditions with OR?
问题描述
在我的 Rails 应用程序中,我遍历一个数组以创建一个必须由 OR 连接的条件列表.以下是我目前的基本流程.
In my Rails app, I loop through an array to create a list of conditions that must be joined by OR. Below is the basic flow of how I currently do so.
conditions = nil
set.each do |value|
condition = value.to_condition
conditions = conditions ? conditions.or(condition) : condition
end
显然,它并不漂亮,但我仍然不完全了解 Arel.它是否提供了对一组动态生成的条件进行 OR-join 的更好方法?
Obviously, it's not beautiful, but I still don't fully know my way around Arel. Does it offer any better way of OR-joining a set of dynamically-generated conditions?
推荐答案
这非常适合 inject
,它会给你一个单行代码,你也可以在其他东西中使用:conditions = set.inject { |conds, cond|conds.or(cond) }
甚至可以写成: set.inject(&:or)
非常好.
This is a perfect fit for an inject
which will give you a one-liner you can use within something else as well:
conditions = set.inject { |conds, cond| conds.or(cond) }
which can even be written: set.inject(&:or)
which is very nice.
这篇关于Arel:如何使用 OR 干净地连接多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!