Wednesday, August 20, 2008

Sanitize_sql_array

The current Rails app I'm working on requires a custom sql in some sections, but writing out query conditions can be hassle sometimes. Using plain old ActiveRecord queries lets you put in conditions in the form of an array consisting of a simple query string containing question marks which are filled in by the parameter which follow the query string in this conditions array.

Example:
:conditions => [" foo = ? AND bar = ? AND baz IN (?)",
single_value_1, single_value_2, array_of_values ]

To use this conditions array for my find_by_sql queries I do this.

conditions_array = [" foo = ? AND bar = ? AND baz IN (?)",
single_value_1, single_value_2, array_of_values ]
condition_string = ActiveRecord::Base.send(
"sanitize_sql_array", conditions_array)

Now I have nice condition_string I'm able to use in my custom queries. I'm not all that experienced with Ruby's handling of scope, so I'm using the send method to access this protected class method. Let me know if there's a nicer way to do this.