Define an array condition that selects on dynamic columns

Updated . Posted . Visible to the public.

For some reason you want to define a find condition in array form. And in that condition both column name and value are coming from user input and need to be sanitized.

Unfortunately this works in SQLite but does not in MySQL:

named_scope :filter, lambda { |attribute, value|
  { :conditions => [ 'articles.? = ?', attribute, value ] }
}

The solution is to use sanitize_sql_array Show archive.org snapshot like this:

named_scope :filter, lambda { |attribute, value|
  { :conditions => sanitize_sql_array([ "`articles`.`%s` = '%s'", attribute, value ]) }
}
Arne Hartherz
Last edit
Daniel Straßner
Keywords
activerecord, rails
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2010-09-15 09:20)