views:

162

answers:

3

In Rails, when I want to find by a user given value and avoid SQL injection (escape apostrophes and the like) I can do something like this:

Post.all(:conditions => ['title = ?', params[:title]])

I know that an unsafe way of doing this (possible SQL injection) is this:

Post.all(:conditions => "title = #{params[:title]}")

My question is, does the following method prevent SQL injection or not?

Post.all(:conditions => {:title => params[:title]})
+5  A: 

Yes, it does. Only the second one is dangerous.

Philipe Fatio
Thank you for your direct response.
yuval
+1  A: 

+1 @fphilipe and @yuval Check this 5 min video from railscast and this one from rails guide

piemesons
Thanks, I've seen this already but it doesn't cover my question (pertaining to the last find)
yuval
+1  A: 

One good reference - http://guides.rubyonrails.org/security.html#sql-injectionlink text

Ed
Thank you, this is relevant.
yuval