patternrubyrailsMinor
Search for products based on criteria
Viewed 0 times
criteriasearchforbasedproducts
Problem
The method must search
The criteria are as follows:
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
endSolution
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
endCode 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
endContext
StackExchange Code Review Q#2716, answer score: 8
Revisions (0)
No revisions yet.