33

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]})
rook
  • 66,304
  • 38
  • 162
  • 239
Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175

3 Answers3

39

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

fphilipe
  • 9,739
  • 1
  • 40
  • 52
8

One good reference from the RoR Guides.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
edthix
  • 1,752
  • 16
  • 18
5

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

Mohit Jain
  • 43,139
  • 57
  • 169
  • 274