class ProductsController < ApplicationController
helper_method :sort_column, :sort_direction
def index
@values = ValuesOfProduct.joined_products.paginate :per_page => 20,
:page => params[:page],
:order => (sort_column + " " + sort_direction),
:conditions => conditions
end
private
def rooms_conditions
["Rooms LIKE ?", "%#{params[:rooms]}%"] if params[:rooms].present?
end
def floor_conditions
["Floor LIKE ?", "%#{params[:floor]}%"] if params[:floor].present?
end
def minimum_area_conditions
["Area >= ?", params[:min_area]] if params[:min_area].present?
end
def maximum_area_conditions
["Area <= ?", params[:max_area]] if params[:max_area].present?
end
def minimum_price_conditions
["TotalBrutto >= ?", params[:min_price]] if params[:min_price].present?
end
def maximum_price_conditions
["TotalBrutto <= ?", params[:max_price]] if params[:max_price].present?
end
def conditions
[conditions_clauses.join(' AND '), *conditions_options]
end
def conditions_clauses
conditions_parts.map { |condition| condition.first }
end
def conditions_options
conditions_parts.map { |condition| condition[1..-1] }.flatten
end
def conditions_parts
private_methods(true).grep(/_conditions$/).map { |m| send(m) }.compact
end
def sort_column
%w[Number Rooms Floor Area TotalBrutto].include?(params[:sort]) ? params[:sort] : "Number"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
end
Refactorings
No refactoring yet !
Les Nightingill
October 10, 2010, October 10, 2010 21:04, permalink
I would suggest that all the xx_conditions methods should be named_scopes, so for example:
class ValuesOfProduct < ActiveRecord::Base
named_scope :with_minimum_area, lambda{|area| {conditions => ['area > ?', area || 0] }}
end
Greg
November 3, 2010, November 03, 2010 15:02, permalink
I agree with Les Nightingill.
This is how I handle null params in a named_scope
named_scope :with_minimum_area, lambda{|area| {
return {} if area.blank? || !area.is_a?(Integer)
{conditions => ['area > ?', area ] }
}
Hi all,
I know that the controller is not right place to put so much code but, I'm not sure how I can pass all the params to the model.
As well I'm not sure whether or not a new model call 'Search' won't be a better solution.
Thanks in advance!