I’ve used Ryan Bate’s search with Ajax episode to write some basic search functionality.
What it basically does is take a string from a form, and performs a like query via a model method. What I’m trying to do is conditionally search to different columns(due_date and name) in the database with a single string that I parse with the Date class. That way a user can search for items by a date, or the item name witht he same form. My method looks like:
def self.search(search)
if search
search_date = Date.parse(search) rescue nil
end
if search_date
where('due_date = ?', search_date)
elsif search
where('UPPER(name) LIKE ?', "%#{search.upcase}%")
else
scoped
end
end
This works, as if the user types in a date, the Date class is able to parse it, an look in the database for any objects that have that due_date. The problem is, if it is a date and it’s able to be parse, the search is incredibly slow.
I was wondering if anyone had a way of speeding this up. Is it the Date class that is so slow? Should I have two different methods? or Should I completely rewrite my search?
I really doubt it’s
Date.parsebeing slow. You should checklog/development.logto see what the query execution times are. What you’re most likely experiencing is a table scan because you’re missing an index ondue_date.Always check slow queries using
EXAMINE. An example:You’ll get some information on the number of rows it will have to sort through, plus any indexes that could be used.