Rails SQL injection?

Yuval Karmi picture Yuval Karmi · Jun 3, 2010 · Viewed 13.3k times · Source

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]})

Answer

fphilipe picture fphilipe · Jun 3, 2010

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