Arel: How to cleanly join multiple conditions with OR?

故事扮演 提交于 2019-12-03 12:29:46

问题


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?


回答1:


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.




回答2:


There is also a useful plugin for this.

conditions_helper

It helps to generate complex conditions.




回答3:


I think that's basically it. I'd initialize conditions to the base object to avoid the ternary:

scope = Article
set.each{|v| scope = scope.or(v.to_condition)}


来源:https://stackoverflow.com/questions/2992393/arel-how-to-cleanly-join-multiple-conditions-with-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!