Search for products based on criteria The method must search Products found by criteria and store them in @products.

The criteria are as follows:


If the user enters something in text_field (:search_keywords) then the product's name needs to be matched with that word
If the user specifies product_type (:product[:type]) then all the found products must be of that type.




def search
  if params[:search_keywords] &amp;&amp; params[:search_keywords] != ""
    @products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
    if params[:product] &amp;&amp; params[:product][:type] &amp;&amp; params[:product][:type] != ""
      @products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
    end
  else
    if params[:product] &amp;&amp; params[:product][:type] &amp;&amp; params[:product][:type] != ""
      @products = Product.find_all_by_product_type_id(params[:product][:type])
    else
      @products = Product.all
    end
  end
end
Try to use scopes, its a lot nicer

def search
  @products = Products.scoped
  if !params[:search_keywords].blank?
    @products = @products.where("name LIKE ?", "%#{params[:search_keywords]}%")
  end
  if !params[:product].try(:[], :type).blank?
    @products = @products.where(:product_type_id =&gt; params[:product][:type])
  end
  @products # maybe @products.all if realy needed
end