Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arel: How to cleanly join multiple conditions with 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

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?

like image 631
Matchu Avatar asked Jun 07 '10 19:06

Matchu


2 Answers

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.

like image 188
einarmagnus Avatar answered Sep 28 '22 01:09

einarmagnus


There is also a useful plugin for this.

conditions_helper

It helps to generate complex conditions.

like image 44
Nick Avatar answered Sep 28 '22 02:09

Nick