Skip to content

Instantly share code, notes, and snippets.

@freshfey
Created April 30, 2012 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freshfey/2556379 to your computer and use it in GitHub Desktop.
Save freshfey/2556379 to your computer and use it in GitHub Desktop.
class Category < ActiveRecord::Base
has_many :topics, :order => "name ASC"
has_many :entries, :through => :topics
# Public: Return an Array of categories with included topics
# and entries as hash values.
#
# search_results - An array of entries
#
# Returns a list of Categories
def self.categories_for_search_result(search_results)
topics = topics_for_entries(search_results)
categories = categories_for_topics(search_results)
result = []
categories.each do |category|
topics.each do |topic|
if topic.category_id == category.id
search_results_array = Array.new
search_results.each do |entry|
if entry.topic_id == topic.id
search_results_array.push(entry)
end
end
@topic_hash = {topic => search_results_array}
end
end
categories_hash = {category => @topic_hash}
result.push(categories_hash)
end
return result
end
private
def self.topics_for_entries(entries)
topics = Array.new
entries.each { |entry| topics.push(entry.topic) }
return topics.uniq
end
def self.categories_for_topics(topics)
categories = Array.new
topics.each { |topic| categories.push(topic.category) }
return categories.uniq
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment