<?xml version="1.0" encoding="UTF-8"?>
<post>
  <body>&lt;p&gt;So I finally got around to replacing the dummy text in the sidebar with real, working archive links, and it was stupidly easy.&amp;nbsp; Check it out...&lt;/p&gt;
&lt;p&gt;First, I added a helper method to take all published posts and group them by the month they were created.&lt;/p&gt;
&lt;pre name="code" class="ruby"&gt;def archives
  @archives = Post.published.in_order.all.group_by { |t| t.created_at.beginning_of_month}
end
&lt;/pre&gt;
&lt;p&gt;Then I used that helper method to display links for each month in which posts were created.&lt;/p&gt;
&lt;pre name="code" class="ruby"&gt;&lt;ul&gt;
  &amp;lt;% archives.each do |month, posts| %&amp;gt;
    &lt;li&gt;&amp;lt;%= link_to(month.strftime('%B')+" (#{posts.size})", archive_path(:month =&amp;gt; month.month, :year =&amp;gt; month.year)) %&amp;gt;&lt;/li&gt;
  &amp;lt;% end %&amp;gt;
&lt;/ul&gt;
&lt;/pre&gt;
&lt;p&gt;You probably noticed the &lt;em&gt;archive_path&lt;/em&gt; named route that the links point to.  Here's how I set it up.&lt;/p&gt;
&lt;pre name="code" class="ruby"&gt;map.archive '/posts/:year/:month', :controller =&amp;gt; 'posts', :action =&amp;gt; 'archive'
&lt;/pre&gt;
&lt;p&gt;That route points to the archive action of the posts controller which merely retrieves the posts created within the specified month and renders the list view.&lt;/p&gt;
&lt;pre name="code" class="ruby"&gt;def archive
  @posts = Post.published.in_order.from_month(Time.parse "#{params[:month]}/#{params[:year]}").paginate(:page =&amp;gt; params[:page], :per_page =&amp;gt; 5)
  render :action =&amp;gt; 'index'
end
&lt;/pre&gt;
&lt;p&gt;The archive action uses a &lt;em&gt;from_month&lt;/em&gt; named scope on the Post model to restrict the find to all posts created within a given month.&lt;/p&gt;
&lt;pre name="code" class="ruby"&gt;named_scope :from_month, lambda { |month| {:conditions =&amp;gt; {:created_at =&amp;gt; month..(month + 1.month)}} }
&lt;/pre&gt;
&lt;p&gt;That's it.  That's all it takes to set up simple archive links for your blog.&lt;/p&gt;</body>
  <created-at type="datetime">2009-04-14T05:07:04Z</created-at>
  <description>So I finally got around to replacing the dummy text in the sidebar with real, working archive links, and it was stupidly easy.? Check it out...



Fir</description>
  <id type="integer">27</id>
  <keywords></keywords>
  <published type="boolean">true</published>
  <slug>archive-links-quick-and-easy</slug>
  <title>Archive links, quick and easy</title>
  <updated-at type="datetime">2009-05-04T14:14:18Z</updated-at>
</post>
