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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)