Searching for at least one word (active record)
I've got a model with let's say two fields: name and subject And i want user can type "Maria chubbb" in the searc开发者_运维百科hbox and application should return every record which has at least one word from search string (or %word%) and it word can be in any of fields. How to achieve that?
If you want to do it with plain ActiveRecord/SQL, you can do it like this:
words = params[:query].split(' ')
# => ["Maria", "chubbb"]
conditions = words.collect {|word| "name LIKE ? OR subject LIKE ?"}.join(" OR ")
# => "name LIKE ? OR subject LIKE ? OR name LIKE ? OR subject LIKE ?"
values = words.collect {|word| ["%#{word}%", "%#{word}%"]}.sum
# => ["%Maria%", "%Maria%", "%chubbb%", "%chubbb%"]
YourModel.where([conditions] + values)
Later, if you want to do it "right", use a search engine such as Sphinx (connected by Ruby/Rails via the thinking_sphinx gem). Then in your model you can define which fields to include in the search like this:
class YourModel < ActiveRecord::Base
define_index do
indexes :name
indexes :subject
end
end
Then you can search like this:
YourModel.search("Maria chubbb")
The advantage here is that search is fast even in a big database and the results can be weighted, for example if both match vs. if only one word matches.
精彩评论