Read more

Define an array condition that selects on dynamic columns

Arne Hartherz
September 15, 2010Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 ]) }
}
Posted by Arne Hartherz to makandra dev (2010-09-15 11:20)