Skip to content

Instantly share code, notes, and snippets.

@carlesso
Created October 31, 2011 11:25
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 carlesso/1327307 to your computer and use it in GitHub Desktop.
Save carlesso/1327307 to your computer and use it in GitHub Desktop.
def hc_votes_per_ages(search_params = {})
# TODO apply search params
# 0-18 19-24 25-34 35-49 50-64 65-inf
now_s = Time.now.to_formatted_s(:db)
age_votes = {"0" => [], "1" => [], "2" => [], "3" => [], "4" => [], "5" => [], "6" => []}
age_labels = {"0" => "< 18", "1" => "18 - 25", "2" => "25 - 35", "3" => "35 - 50", "4" => "50 - 65", "5" => "> 65", "6" => "unknown"}
model.answers.each do |a|
query = "COUNT(users.id) as vote_count, CASE
WHEN users.birthday>(NOW() - INTERVAL '18 year') THEN 0
WHEN users.birthday<=(NOW() - INTERVAL '18 year') AND users.birthday>(NOW() - INTERVAL '25 year') THEN 1
WHEN users.birthday<=(NOW() - INTERVAL '25 year') AND users.birthday>(NOW() - INTERVAL '35 year') THEN 2
WHEN users.birthday<=(NOW() - INTERVAL '35 year') AND users.birthday>(NOW() - INTERVAL '50 year') THEN 3
WHEN users.birthday<=(NOW() - INTERVAL '50 year') AND users.birthday>(NOW() - INTERVAL '65 year') THEN 4
WHEN users.birthday<=(NOW() - INTERVAL '65 year') THEN 5
ELSE 6
END"
col = {}
all_ages = age_votes.keys
a.scoped_votes(search_params).joins(:user).select(query).group{"\"case\""}.each do |s|
all_ages.delete s.case.to_s
age_votes[s.case.to_s] << s.vote_count.to_i
end
all_ages.each do |v|
age_votes[v] << 0
end
end
res = []
age_votes.each do |k, v|
res << {:name => age_labels[k], :data => v}
end
res
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment