When I want to do OR-queries with DataMapper I use
result = MyModel.all(:first_name.like => '%john%') + MyModel.all(:last_name.like => '%john%')
This works fine and generates only one SQL query.
How can I create the same result with properties given in an array?
result = [ :first_name, :last_name ].reduce([]) do |sum, prop|
sum + MyModel.all(prop.like => '%john%')
end
Although this works, it uses two separate SQL queries which is not what I want. Is there a way to create such a “lazy” query in a loop?
I figured it out myself. The problem is that you cannot use an empty regular array (
[]) as the initial value of the result variable. I did not want to dig into the DataMapper internals too deeply, so I just used additional checking for the first assignment ofresult, like this: