Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_by_sql and single quotes in an ORDER BY clause

Rails 2.3.5

I know I should be doing find_by_sql with sanatized variables like:

sql = %Q{
SELECT blah
FROM blah
ORDER BY ? DESC
      } 

But, since the variable will be single quoted, the ORDER BY clause won't work. I know that un-sanitized I could just do:

sql = %Q{
SELECT blah
FROM blah
ORDER BY #{params[:sort]} DESC
      }

What's the best way to handle needing a sanatized varialbe in an ORDER BY clause? Thanks!

like image 449
Reno Avatar asked Dec 13 '25 01:12

Reno


1 Answers

Maybe a little hack but i escape params sometimes like this.

sql = AnyActiveRecordModel.send(:sanitize_sql_array, ["SELECT blah FROM blah ORDER BY ? DESC", params[:sort])

sanitize_sql_array is a private class method of an active record model and like this you can access it. It is the same method which is used in the conditions in a AR find

AnyActiveRecordModel.find(:all, :conditions => ["condition = ?",params[:blah]]

It is dirty but i didnt know to solve it in a better way and I had a time limit :P

like image 147
Michael Koper Avatar answered Dec 15 '25 17:12

Michael Koper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!