Building the SQL WHERE clause dynamically in Rails
Over on the Rails mailing list, Rafał Komorowski asks How to programatically build :contitions with elegance?
His problem is a form with four conditions. Each may be applied, but any or all of them may be set to “All”.
The brute force way of doing this would be:Note that in this case, you have to pay attention to the order in which you evaluate your conditions. If you put params[:cond1] before params[:cond1] && params[:cond2], and params[:cond1] is true, Ruby will only evaluate the params[:cond1] branch.
['1=1']. This is to prevent a problem later on when Rails evaluates the conditions option to find . If we leave the array empty, Rails will append the WHERE empty condition, generating something like this:
The database backend will complain with a syntax error.
This discussion aside, I believe this is clear and concise code. Ain’t Ruby fun ?
October 12th, 2007 at 10:25 PM
Erm… how about simply checking for an empty conditions array and choosing the proper find method accordingly? The superfluous “1=1” might get optimized away by some databases, but it’s not very elegant.
October 12th, 2007 at 10:25 PM
Of course, that is possible. Removing a conditional in my code means one less thing to test and worry about.
The less code I write, the better I feel. That’s all.
October 12th, 2007 at 10:25 PM
Hm, I see. Still would have done it differently ;)