How can you do a conditional where clause using AREL

kidbrax picture kidbrax · Jun 3, 2011 · Viewed 13.5k times · Source

How can you do a conditional where clause? I have a rake task that runs a query. Say I am building a query like so:

residentials = Residential.where(:is_active => true)

Now if I pass a certain parameter to the rake task, I want to add to the where clause. I was thinking something like this:

residentials.where(:something_else => true) if param_was_passed

But that just replaces the existing where clause. How can I add it to the existing where clauses?

Answer

Bert Goethals picture Bert Goethals · Jun 3, 2011

It is possible to chain where statements

residentials = Residential.where(:is_active => true)
residentials = residentials.where(:other_thing => true) if param_was_passed

This should work.

Make sure this is not the last line in a function call; repeat the residentials variable as the last line in that case. (As per @digger69 comment)