I have a database with Product
and product has a name
attribute which I want to search. Im using a scope to do that:
scope name_contains, lambda{|q| where("name LIKE ?", "%#{q}%")}
which works fine when I search for "Awesome Product" and the product is called "A pretty Awesome Product" but not when I search for "product awesome" because the words are in the wrong direction. What I tried next was splitting the query by space and call the scope for every word:
def self.search(q)
q.split(" ").map(&:strip).select{|x| !x.empty? }.each_with_index do |word,index|
if index == 0
data = Product.name_contains(word)
else
data = data.name_contains(word)
end
end
data
end
Which works but it hits the database for every word. But I know rails can handle this better because this:
Product.name_contains("awesome").name_contains("product")
hits the database only once. This is what I want but can't realize when calling the name_contains
method in an iteration.