Hello
In Rails Cookbook is example of live search.
There is one input field and we are looking for word (words) in TITLE
column.
code:
def self.search(terms)
find :all,
:conditions =>
[([“(LOWER(title) LIKE ?)”] * terms.size ).join(" AND "), *
terms.flatten]
end
terms is an array with word (words)
My question is:
How to change SEARCH function to search word (words) in more then one
column eg. TITLE, BODY …
Greate example of live search is here: www.gotapi.com
Greetings
This is so ugly, I can’t believe I’m posting it…
[ “(” + ([“LOWER(title) LIKE ?”] * terms.size).join(" AND “) + “)” + "
OR " + “(” + ([“LOWER(body) LIKE ?”] * terms.size).join(” AND ") +
“)”, * terms.flatten * 2 ]
Be careful with the line breaks or it won’t work.
One problem with this (besides the field names being hard coded and it
being a big, ugly mess) is that it will only find matches for one
field. In other words, if a user entered “My favorite poem”, there
would only be a match if all of those words were in the title OR if
all of those words were in the body - it won’t find the “poem” if its
title is “My Favorite Things” and the body contains “poem”.
Also, I assume that you have something like this in your code to put
the wildcard characters in with your search terms:
terms.map {|t| “%#{t}%”}
If you’re doing more advanced searching, you might look into some
plugins. I’ve heard many people talk about acts_as_ferret (with mixed
reactions). Another option could be to allow the user to select what
field he wants to search with a radio button list that corresponds to
the possible search fields. You could then pass this value into a
“field” variable for the search (i.e., “LOWER(#{field}) LIKE ?”…).
If you need something to work quickly, go ahead and try my solution.
If you need something to work well, you might want to look
elsewhere.
-Kyle