Reputation: 808
I've been working on this search form for an app I'm building to learn Rails.
It's supposed to search for products but when I enter some product name in the search field it gives me a list of all products. The solution is probably simple but I haven't figure it out yet and I'm getting pretty frustrated.
I tried to change @products to a different name but that didn't work.
Can someone check this out and advise me please?
thanks in advance D
in my _navbar the code is
<%= form_tag search_products_path, class: 'navbar-form navbar-right' do %>
<%= search_field_tag class: 'form-control', :id => 'searchbar', :placeholder =>'Search', :name => "query" %>
<%= submit_tag "Submit", class: 'btn btn-default', :name => nil %>
<% end %>
in my views/products/search.html.erb
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Designer</th>
<th>Price</th>
<th>Stock</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= link_to product.name, product %></td>
<td><%= product.description %></td>
<td><%= product.designer.designer_name %></td>
<td><%= number_to_currency product.price %></td>
<td><%= product.stock_quantity %></td>
<td><%= image_tag product.image.thumb %></td>
<% end %>
</tr>
</tbody>
in my product.rb model I have this code
class Product < ActiveRecord::Base
mount_uploader :image, ImageUploader
validates_presence_of :name, :price, :stock_quantity
validates_numericality_of :price, :stock_quantity
belongs_to :designer
belongs_to :category
belongs_to :page
def self.search(query)
where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%")
end
end
In the products_controller.rb I have this code
def search
@products = Product.search(params[:query])
@categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct
end
Upvotes: 0
Views: 599
Reputation: 1278
instead of using
@q = "%#{params[:query]}%"
@products = Product.where("name ILIKE ? or description ILIKE ?", @q, @q)
use
@products = Product.search(params[:query])
in model change the code to
"name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%"
Upvotes: 0