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.