Yuval Karmi
Yuval Karmi

Reputation: 26723

Rails SQL injection?

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

Upvotes: 33

Views: 13613

Answers (3)

edthix
edthix

Reputation: 1752

One good reference from the RoR Guides.

Upvotes: 8

Mohit Jain
Mohit Jain

Reputation: 43959

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

Upvotes: 5

fphilipe
fphilipe

Reputation: 10054

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

Upvotes: 39

Related Questions