Just be aware that any time you use a condition like LIKE ‘%foo%’ the
entire table (or index) will be scanned. If the table is large
(thousands of names), it might make better sense to use fulltext
searching. A hybrid way that I’ve used is to generate my own indexes.
Great point. I’ll consider converting it over. Does Rails have
support for fulltext queries?
sanitize_sql is not necessary when you use parameter substitution, as
you’re doing.
From my tests the following causes a SQL error:
options[:order] = [“name = ? DESC”, params[:username]]
Because the resulting SQL is:
ORDER BY name = ? DESCbob
And entering the value into the :order string doesn’t sanitize it:
options[:order] = “name = ‘#{params[:username]}’ DESC”
So the only solution I could see is using the sanitize_sql function.
If there’s a simpler way, I’d love to know.
if params.has_key?(“username”) && !params[:username].nil?
conditions = “name LIKE :name”
Does that work? I would’ve thought you needed %'s in there. And I
don’t understand :name.
It seems to add the ‘%’ characters for me. The resulting SQL is:
name LIKE ‘%bob%’
The :name is for sanitized replacement, similar to the ‘?’. Here’s
how it goes together in a find statement:
User.find(:all, :conditions => [“name LIKE :name AND foo = :bar”,
{:name => “bob”, :foo => “baz”}]
No, the :order part has to be an exact or prefix match to put the
exact match at the top. Plus I think there’s some %'s needed there,
too.
Good catch, thanks!
Thanks for all the help!