Reputation: 32061
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:
Upvotes: 2
Views: 969
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