Вопрос

I want to feed an AMcharts pie chart with data that gives a break down of where the senders of a user's messages are from.

The output should look like this:

"[{country: \"US\", usercount: 25},{country: \"UK\", usercount: 15},{country: \"Italy\", usercount: 10},{country: \"Poland\", usercount: 2},{country: \"Japan\", usercount: 5}]"

So I need to take current_user.messages, get the senders of each of them, find out which countries they are from, count how many from each country, then the compile country names and the user count into an array that I can then loop through, into this string format... phew. Help welcome.

Association schema as requested:

class User < ActiveRecord::Base
  belongs_to :country
  has_many :messages
end

class Message < ActiveRecord::Base
  belongs_to :user
end

class Country < ActiveRecord::Base
  attr_accessible :name, #[...]

  has_many :users

  #table is pre-populated with a list of all the world's countries
end
Это было полезно?

Решение

user_ids = current_user.messages.collect(&:user_id)


country_count_hash = {}
users_ids.each do |user_id|
  country = User.find(user_id).country
  next unless country
  country_count_hash[country.name] ||= 0
  country_count_hash[country.name] += 1 
end

count_array = []
country_count_hash.each do |key, value|
  count_array << {:country => key, :usercount => value}
end

count_array.to_json

That should do it. Please note that its not tested. But it should atleast give you an idea. Doing it in sql would be a good idea if you have lot of users.

Другие советы

I would probably do this with a partial sql statement, and a subquery, as it's a bit expensive operation in pure active record.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top