Enumerable#inject
使用:
@posts_by_months = @posts_by_months.inject({}) do |h,(k,v)|
h[k] = v.sort do |x,y|
y.created_at <=> x.created_at
end
h
end
例如:
irb(main):054:0> hash = @posts_by_months.inject({}) {|h,(k,v)| h[k] = v.sort {|x,y| y.created_at <=> x.created_at}; h}
#=> […]
irb(main):055:0> pp hash.first.map(&:created_at)
[Wed, 08 Jun 2016 22:26:34 UTC +00:00,
Wed, 08 Jun 2016 21:49:49 UTC +00:00,
Wed, 08 Jun 2016 18:30:44 UTC +00:00,
Wed, 08 Jun 2016 18:25:40 UTC +00:00]
UPDATE
Works的導軌經由控制器查看。
# app/controllers/website_controller.rb
class WebsiteController < ApplicationController
def test
@posts = Post.order("created_at desc")
@posts_by_months = @posts.group_by {|t| t.created_at.beginning_of_month}
@posts_by_months = @posts_by_months.inject({}) do |h,(k,v)|
h[k] = v.sort do |x,y|
y.created_at <=> x.created_at
end
h
end
render(:layout => false, :template => 'website/test')
end
end
使用HAML(http://haml.info)模板:
# app/views/website/test.html.haml
- @posts_by_months.sort.each do |month, posts|
= month.strftime('%b')
%br
%ul
- for post in posts
%li
= post.title
![Screenshot of "test.html.haml"](https://i.stack.imgur.com/K30Rf.png)
這是爲'Post.order一樣簡單( 'MONTH(created_at),created_at desc')'? –