How to compile and execute a SQL query SAFELY?

u = Users.new #<ActiveRecord Model>
x = '3; delete from users' # user-supplied data, which is supposed to
be an integer
u.connection.execute("select * from users where id = #{x}") # deletes
ALL records

How would one guard against this SQL injection?

The best way I found so far is to use the quote method as follows:

u.connection.execute("select * from users where id = #{u.quote x}")

Is there a preferred/safer/better way?

-pachl

Users.find(x)

clintpachl <clintpachl@...> writes:

u = Users.new #<ActiveRecord Model>
x = '3; delete from users' # user-supplied data, which is supposed to
be an integer
u.connection.execute("select * from users where id = #{x}") # deletes
ALL records

How would one guard against this SQL injection?

In the case of an ID:

User.find(supposed_id)

otherwise ActiveRecord has a built-in way to escape SQL:

User.find(:all, :conditions => ["my_field = ?", supposed_field])

See http://api.rubyonrails.org/classes/ActiveRecord/Base.html for details

Gareth