Rails is this query open to sql injection?

activerecord, ruby, ruby-on-rails, ruby-on-rails-3, sql-injection

Solution

You should just use the preferred way of including parameters to be safe. Check out this guide:

Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, `Client.where("first_name LIKE '%#{params[:first_name]}%'")` is not safe. See the next section for the preferred way to handle conditions using an array.

Try:

@arrangements_for_month = Arrangement.joins(:timeslot)
  .where("timeslots.timeslot BETWEEN ? AND ?", month, month.end_of_month)
  .order('location_id')

And just a heads up, if you like, there is an alternative way to define a range condition like that using ruby ranges, as described in that section of the linked guide:

Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight)

So, without knowing anything else about your code, you can probably do something like this:

@arrangements_for_month = Arrangement.joins(:timeslot)
  .where("timeslots.timeslot" => month .. month.end_of_month)
  .order('location_id')

Problem

I'm still learning how to write good queries using ActiveRecord. I'm curious if this query is subject to sql injection because of the way i'm using the date field in the query. Can someone please point out any obvious mistakes or any better ways to write this query? ``` @arrangements_for_month = Arrangement.joins(:timeslot). where("timeslots.timeslot BETWEEN '#{month}' AND '#{month.end_of_month}'", params[:id]). order('location_id') ```

Original source