HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Search for products based on criteria

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
criteriasearchforbasedproducts

Problem

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] && params[:search_keywords] != ""
    @products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
    if params[:product] && params[:product][:type] && params[:product][:type] != ""
      @products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
    end
  else
    if params[:product] && params[:product][:type] && params[:product][:type] != ""
      @products = Product.find_all_by_product_type_id(params[:product][:type])
    else
      @products = Product.all
    end
  end
end

Solution

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 => params[:product][:type])
  end
  @products # maybe @products.all if realy needed
end

Code Snippets

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 => params[:product][:type])
  end
  @products # maybe @products.all if realy needed
end

Context

StackExchange Code Review Q#2716, answer score: 8

Revisions (0)

No revisions yet.