Skip to content

Instantly share code, notes, and snippets.

@joho
Created March 25, 2011 04:28
Show Gist options
  • Select an option

  • Save joho/886363 to your computer and use it in GitHub Desktop.

Select an option

Save joho/886363 to your computer and use it in GitHub Desktop.
# args can be :sort_by, :order, :total, :page and :per_page
def self.find_with_categories(site, category, args = {})
raise "order has to be asc or desc, it was #{args[:order]}" unless %w(asc desc).include?(args[:order])
# calculate the order by clause
order = args[:order]
sort_by = args[:sort_by]
order_by = "#{connection.quote_column_name(sort_by)} #{order}"
if sort_by == 'average_rating'
order_by << ', rating_count desc'
end
if %w[username category sales_count average_rating cost].include?(sort_by)
order_by << ', name asc'
end
if category && !category.parent
#It's a root category, we can search root category field
conditions = ["site = ? and root_category = ?", site.domain, category.path]
elsif category
#Use a like query
conditions = ["site = ? and category like '#{category.path}%'", site.domain]
else
#Don't worry about categories at all
conditions = ["site = ?", site.domain]
end
paginate :conditions => conditions,
:order => order_by,
:total_entries => args[:total], :page => args[:page], :per_page => args[:per_page]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment