Grouping and sorting Active Records in Ruby
I have made a few changes to my blog recently, one of them being a list of posts on the right hand side. I had some difficulties with it as I am still new to Ruby and couldn’t find any examples. So here is mine, this is a nice simple way to group Posts by year and month.
<% Post.all .group_by{|ar| ar.created_at.strftime "%Y %b" } .each do |date_str, post_for_month| %> <%= date_str %>
-
<% post_for_month.each do |post| %>
- <%= link_to(post.title, post_path(post)) %> <% end %>
The expected output will be
2011 January
- post title one
- post title two
2011 February
- post title one
If you want to sort by date as well simply change the code above to this
<% Post .order("created_at DESC") .group_by{|ar| ar.created_at.strftime "%Y %b" } .each do |date_str, post_for_month| %> <%= date_str %>
-
<% post_for_month.each do |post| %>
- <%= link_to(post.title, post_path(post)) %> <% end %>
More information can be found here and here
-Matt