0

I have a function which runs a Conditional where query using a hash in order to chain conditions with an AND also.

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:

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.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • This might help, `arel` is somewhat complicated compared to standard AR, but it allows you to do it. http://stackoverflow.com/questions/7976358/activerecord-arel-or-condition – D-side Nov 22 '14 at 23:20

1 Answers1

1

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]).

Another way of doing the same thing is using a block:

ary[1..-1].inject(Object.where(ary[0])) { |query, cond| query.or(cond) }
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93