jjjjjjjj
jjjjjjjj

Reputation: 4523

simple rails search form not working

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:

enter image description here

"Les résultats sont" in the terminal means "the results are..." and then empty, because it returns nothing. What could be wrong here?

Upvotes: 0

Views: 404

Answers (2)

Shadow Radiance
Shadow Radiance

Reputation: 1369

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}%")

Upvotes: 1

Himberjack
Himberjack

Reputation: 5802

Why don't you do lower(?) and search_term.downcase to make sure its not case sensitive

Upvotes: 1

Related Questions