Arel:如何用 OR 干净地连接多个条件?
在我的 Rails 应用程序中,我循环遍历一个数组来创建必须由 OR 连接的条件列表。以下是我目前这样做的基本流程。
conditions = nil
set.each do |value|
condition = value.to_condition
conditions = conditions ? conditions.or(condition) : condition
end
显然,它并不美丽,但我仍然不完全了解阿雷尔周围的路。它是否提供了更好的方式来或连接一组动态生成的条件?
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这非常适合
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.还有一个有用的插件。
conditions_helper
它有助于生成复杂的条件。
There is also a useful plugin for this.
conditions_helper
It helps to generate complex conditions.
我想基本上就是这样。我将初始化基础对象的条件以避免三元:
I think that's basically it. I'd initialize conditions to the base object to avoid the ternary: