JZ.
JZ.

Reputation: 21877

Activerecord: Is this MySQL safe? If not how can I sanitize it?

I'm using the find_by_sql method, and I'm not sure if what I am doing is safe? If its not how can I sanitize my variables?

Table.find_by_sql("SELECT * FROM TABELS
     WHERE table.`table_id` = '#{params[:table]}'
           and insights.`created_at` >= '#{@stime}'
           and insights.`created_at` <= '#{@etime}'
     GROUP BY places.`id`
     ORDER BY sum(insights.`checkins`) DESC").paginate(:page => params[:page], :per_page => Place.per_page)

Upvotes: 1

Views: 439

Answers (1)

Zabba
Zabba

Reputation: 65467

Your SQL is currently not safe. Do this instead:

Table.find_by_sql(["SELECT * FROM TABLES
     WHERE table.`table_id` = '?'
           and insights.`created_at` >= '?'
           and insights.`created_at` <= '?'
     GROUP BY places.`id`
     ORDER BY sum(insights.`checkins`) DESC",
         params[:table],
         @stime,
         @etime]).
     paginate(:page => params[:page], :per_page => Place.per_page)

Note that the param to find_by_sql is an array : the first element is the SQL string, the rest are the parameters, in order.

Upvotes: 5

Related Questions