I have a very simple, typical search form in rails. Input a string, and it checks a column for that model if any strings match it. A few weeks ago it was working just fine. I came back today, and suddenly doesn't work.
Here is my code. My search form:
<%= form_tag("/search/products", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
My Controller:
def search
term = params[:q]
puts "the term is #{term}"
@resultats = Product.search_products(term)
end
In my model, the search_products method:
def self.search_products(search_term)
if search_term == ""
return []
else
where("name LIKE ?", "%#{search_term}")
end
end
in the controller code, the puts "the term is #{term} prints the correct term every time. So I know that is being picked up correctly. just, when i search for something, it doesn't return the correct results. Here is a screenshot from my terminal:
"Les résultats sont" in the terminal means "the results are..." and then empty, because it returns nothing. What could be wrong here?
Your code currently searches for LIKE '%term'
(string must end in term)
You probably need to have it search for LIKE '%term%'
(string must contain term)
Just add a %:
where("name LIKE ?", "%#{search_term}%")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments