Define an array condition that selects on dynamic columns

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:

scope :filter, ->(attribute, value) { where([ 'articles.? = ?', attribute, value ]) }

The solution is to use sanitize_sql_array like this:

scope :filter, ->(attribute, value) {
  where(sanitize_sql_array([ "`articles`.`%s` = '%s'", attribute, value ]))
}

转自

Define an array condition that selects on dynamic columns

如果觉得我的文章对您有用,请在支付宝公益平台找个项目捐点钱。 @Victor Jun 1, 2015

奉献爱心