def self.paged_search(query, from, category, locality, page, per_page = 10)
query_str = []
query_prms = []
if from
query_str << "created_at > ?"
query_prms << from
end
unless locality.blank?
unless locality.is_a?(Array)
l = Locality.find(locality)
locality = l.direct_children.collect {|i| i.id } << l.id if l.direct_children.size > 0
end
query_str << "locality_id IN (?)"
query_prms << locality
end
unless category.blank?
unless category.is_a?(Array)
c = Category.find(category)
category = c.direct_children.collect {|i| i.id } << c.id if c.direct_children.size > 0
end
query_str << "category_assignments.category_id IN (?)"
query_prms << category
end
conditions = [query_str.join(" AND ")] + query_prms
if query.blank?
companies = Company.paginate(:conditions=> conditions, :page => page, :joins => :category_assignments, :per_page => per_page)
else
companies = Company.find_by_contents(query, {:page => page, :per_page => per_page}, :joins => :category_assignments, :conditions => conditions )
end
return companies.uniq
end
Refactorings
No refactoring yet !
This code has multiple flaws:
- Joins with Category and Location are done horribly (inefficiently)
- at the end one Company can be returned multiple times - use of uniq() at the end
- it is all too long and barely testable
Any ideas how to make it work?