Snowman
Snowman

Reputation: 32061

Rails LIKE query not working

This works correctly, and returns correct results:

query = params[:query].downcase
users = User.find(:all, :conditions => ['username LIKE ?', "%#{query}%"])

However, I think this is unsafe as it is open to SQL injection attacks?

So I'm trying to do to it like this:

users = User.all(:conditions => ["username LIKE ?", query])

or even

users = User.where("username LIKE ?", query)

but neither of those 2 return any results.

What's the correct way to do this?

Edit: This works:

users = User.where("username LIKE ?", "%#{query}%")

But according to Rails docs:

enter image description here

Upvotes: 2

Views: 969

Answers (1)

Gavin Miller
Gavin Miller

Reputation: 43815

You're missing the percentage symbol in your alternative attempts at the query:

query = "%thing_to_find%"
users = User.all(:conditions => ["username LIKE ?", query])

-or-

query = "%thing_to_find%"
users = User.where("username LIKE ?", query)

But with that said, your first example is safe from SQL injection. In fact all three of your examples are AOK!

Upvotes: 6

Related Questions