Creating an archive for your blog posts can be fun. But first, you’ll have to understand ActiveRecord’s group_by method.
Creating a Google Sitemap for your Rails blog is another good SEO step to consider. Showing Google where to find your posts is wise Rails-fu and will set the stage for your blog’s archive.
Rails ActiveRecord Group_By
Learning to group a collection of your posts by month can be confusing at first. Using Rails’ ActiveRecord group_by method is the key to success here. Let’s get started:
The code gets your collection of posts. Then it gets each post’s corresponding post date.
Also, notice the code brings back only the data needed instead of the entire object graph. This decreases latency and thus, increases speed.
Another feature of this code is I’m grouping by month. Now, this may sound more purpose than feature, but it actually means something significant. Grouping by month ensures the list is chronological, even when a new year starts.
This will display a month, then list each blog post for that month. When complete, it will list the next month, etc. Initially, your posts will display from oldest to newest. If that’s what you want, then you’re done.
But, if you’re like me, you want to display your blog archive posts from newest to oldest. To accomplish this, you need to reverse your collection using Ruby’s reverse string function.
That’s it! Good luck and happy coding!