I am trying to allow the end-user of a rails app to limit results based on the value of an arbitrary column. At its simplest, I want to do something roughly equivalent to:
"SELECT * FROM products WHERE (#{params[:min_col]} >= #{params[:min]})"
without the injection vulnerability.
For example, example.com/myapp/catalog?min_col=sell_price&min=300 would return all products with sell_price greater than or equal to $3.00
I tried adding a scope like this to the model:
->(column,min) { where("? >= ?", column, min) }
and passing the uri parameters to that scope, but this yields
WHERE ('sell_price' >= '300')
which seems to just be comparing two literal strings -- this query and others like it always return every row or no rows. How do I get the desired behavior of comparing against a column specified in params?
?escape will always convert the Ruby type into the corresponding SQL type. Ergo the quotes for strings. I thought a symbol might work but tried and found it does not. You get the quotes for the symbol as well.