假设我有一个包含created_at,title和id的帖子模型。我如何建立一个多年的数组>几个月>用于展示档案的帖子。
到目前为止,我有:
@posts = Post.all(:order => 'created_at DESC')
@post_months = @posts.group_by { |t| t.created_at.beginning_of_month }
这给了我类似{“June 2012”=> {“post1”,“post2”}}即将结束。
http://shouweick.blogspot.co.uk/2012/02/handling-background-jobs-in-rails-32.html此博客的输出格式为{year => {november => {post1,post2},december => {post3}}}
答案 0 :(得分:2)
首先按年份分组,然后按月对这些群组进行分组:
Hash[
x.group_by{|x| x.created_at.year}
.map{|k,v| [k,v.group_by{|x| x.created_at.month}]}
]