我有一堆帖子里面有类别标签.我试图找出每个类别被使用了多少次.
我正在使用带有mongodb的rails,但我不认为我需要从db中获取类别的出现,因此mongo部分应该无关紧要.
这就是我到目前为止所拥有的
@recent_posts = current_user.recent_posts #returns the 10 most recent posts
@categories_hash = {'tech' => 0, 'world' => 0, 'entertainment' => 0, 'sports' => 0}
@recent_posts do |cat|
cat.categories.each do |addCat|
@categories_hash.increment(addCat) #obviously this is where I'm having problems
end
end
end
这个职位的结构是
{"_id" : ObjectId("idnumber"), "created_at" : "Tue Aug 03...", "categories" :["world", "sports"], "message" : "the text of the post", "poster_id" : ObjectId("idOfUserPoster"), "voters" : []}
我愿意接受关于如何获得类别数量的建议,但我想最终获得选民的数量,所以在我看来最好的方法是增加categories_hash,然后添加votes.length,但有一件事,我只是想弄清楚如何增加哈希值.
如果您不熟悉map/reduce并且不关心扩展,那么这不像map/reduce那么优雅,但对于小型站点应该足够了:
@categories_hash = Hash.new(0)
current_user.recent_posts.each do |post|
post.categories.each do |category|
@categories_hash[category] += 1
end
end
Run Code Online (Sandbox Code Playgroud)