views:

94

answers:

2

hi

i have some conditions to pass to a finder. The problem is that i don't want to pass in an usafety way. So imagine that i receive a hash:

hash = {:start_date=>'2009-11-01',:end_date=>'2010-01-23'}

i would like to pass it to my finder like:

Model.find(:all,:conditions=>"created > '#{start_date}' and created < '#{end_date}'")

The problem is that it is unsafe and i'm exposed to SQL injection problems. My question is, how would be the best way to compose this condition?

I want to do it dynamically. For example, i'm doing today like:

find_condition = ['created > ? and created < ?','2009-10-01','2010-01-01']
Model.find(:all,:conditions=>find_condition)
+4  A: 

You can write it like this:

Model.find(:all,:conditions=>["created > :start_date and created < :end_date", {:start_date => params[:one], :end_date => params[:two]}])

It will be escaped properly.

Tomas Markauskas
+1  A: 

Active Record supports escaping of conditions using a question mark:

Model.all(:conditions => ['created > ? and created < ?',
          :start_date, :end_date])

Some further information in the Rails' Guides that you may be interested in:

John Topley
@JohnTopley I think that should actually be `Model.all(:conditions => ['created > ? and created < ?', :start_date, :end_date])`. (i.e. don't the conditions belong in the `[]` as well?)
jerhinesmith
@jerhinesmith Thanks, good catch! I'll update the example.
John Topley
I believe you meant start_date, end_date instead of :start_date, :end_date (colons out)
egarcia
@egarcia I believe it will work using either form.
John Topley
@JohnTopley Interesting - how is that possible? Wouldn't the '?' be just replaced by the text 'start_date' and 'end_date' respectively?
egarcia