我想向AMcharts饼图提供数据,这些数据可以细分用户消息的发送者的来源。
输出应如下所示:
"[{country: \"US\", usercount: 25},{country: \"UK\", usercount: 15},{country: \"Italy\", usercount: 10},{country: \"Poland\", usercount: 2},{country: \"Japan\", usercount: 5}]"因此,我需要使用current_user.messages,获取每个发件人的发件人,找出他们来自哪些国家,计算每个国家有多少人,然后将国家名称和用户计数编译成一个数组,然后我可以遍历该数组,将其转换为以下字符串格式...呼。欢迎光临。
请求的关联架构:
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发布于 2013-06-22 06:35:16
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这应该就行了。请注意,这是未经测试的。但它至少应该给你一个概念。如果你有很多用户,用sql做这件事会是个好主意。
发布于 2013-06-22 05:24:38
我可能会使用部分sql语句和子查询来实现这一点,因为在纯活动记录中这是一个开销很大的操作。
https://stackoverflow.com/questions/17243585
复制相似问题