0
votes

I have two controller categories and products, relation is category has_many products in application.html.erb catagory dropdown menu and form_tag for search products. My requirement is when I selected any category name through dropdown menu and search any products, should show that categories product. if I will not select any category at that time of finding any product it should show products which is releated to all category.

application.html.erb

<select>
 <option value>Catagory by Name</option>
 <option value="Samsung">Samsung</option>
 <option value="Nokia">Nokia</option>
 <option value="Apple">Apple</option>
 <option value="HTC">HTC</option>
 <option value="Sony">Sony</option>
 <option value="Blackbarry">Blackbarry</option>
</select>


<tr><%= form_tag products_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search,params[:search],placeholder: "Search Products"%>
    <%= submit_tag "search",:name => nil %>
  </p>
 <% end %></tr>

product_controller.rb

def index
  @products = Product.all
  if params[:search]
   @products = Product.search(params[:search])
  else
   @products = Product.all
  end
end

product.rb

def self.search(search)
  where("name like ?", "%#{search}%")
end

So please give me idea how to solve it.

2

2 Answers

0
votes

You can use a form_tag and include that drop down menu in it along with the search. Then in your controller you can construct a query from that dropdown menu selection.

0
votes

You can put category to dropdown menu with select_tag and use options_for_select on your search form. You can read about select_tag with option_for_select here

<%= form_tag products_path, :method => 'get' do %>
  <p>
    <%= select_tag :category_id, options_for_select([["Catagory by Name", nil]] + Category.all.collect {|x| [x.name, x.id]}),{} %>
    <%= text_field_tag :search, params[:search], placeholder: "Search Products"%>
    <%= submit_tag "search",:name => nil %>
  </p>
<% end %>

You don't need @products = Product.all and logic if params[:search] just use this :

products_controller.rb

def index
  @products = Product.search(params[:category_id],params[:search])
end

And on product.rb looks like this :

def self.search(category, search)
 if search
    if category == nil
      where("name like ?", "%#{search}%")
    else
      where("category_id = ? OR name like ?", category, "%#{search}%")
    end 
 else
    # use scoped will get Product.all
    scoped
 end  
end

Note : this not tested but hope this help you.