Skip to content

Instantly share code, notes, and snippets.

@paulleader
Created May 30, 2012 10:22
Show Gist options
  • Save paulleader/2835342 to your computer and use it in GitHub Desktop.
Save paulleader/2835342 to your computer and use it in GitHub Desktop.
Facet count for an arbitrary dimension on the results of a search, uses #where_values
def facet_count(facet)
# Work out some useful strings.
facet_table = facet.table_name
facet_sym = facet_table.to_sym
facet_id_name = facet.name.foreign_key
# Build the base query in terms of the
# model being used to facet the results.
#
# We join to Company as that is used to filter
# out inactive companies.
facet_counts = facet.
joins(:antibodies => :company).
group("#{facet_table}.id").
select(
"#{facet_table}.id id, #{facet_table}.name, #{facet_id_name}, count(*) count"
).order('count DESC')
# Take the Antibodies scope, resulting from the
# search, and apply its clauses to
scoped.where_values.each do |condition|
facet_counts = facet_counts.where(condition)
end
# Convert into a thing/count pair
facets.collect {|a| [a, a.count]}
end
@paulleader
Copy link
Author

The 'facet' parameter should be a model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment