title: Group records by both month and year in Rails
body: <p>I'm on Ruby 1.9.2, Rails 3.0.x and I use MySQL DB. I have a Messages Model, where one can post new messages every day. </p>
  
  <p>I have an index action where I want to display these messages grouped by both month and year. This basically is used to filter messages.</p>
  
  <p>My query looks like this:-</p>
  
  <pre><code>@active_msgs = Messages.where('expiry &gt; ?', Time.now).order('created_at DESC')
  </code></pre>
  
  <p>I used the group_by function in Rails, after referring to <a href="https://stackoverflow.com/questions/902974/grouping-by-week-month-etc-activerecord">this post</a></p>
  
  <p>My Group By Query is:-</p>
  
  <pre><code>@msgs_by_month = @active_msgs.all.group_by {|u| u.created_at.month }
  </code></pre>
  
  <p>I was returned a Hash called @msgs_by_month. This helped me group the messages by month, but  I need to taken into account the year, <strong>to form a unique key</strong> , as it would help me differentiate between for e.g., Sept 2011 and Sept 2012. </p>
  
  <p>My current key only is of type Hash[Month] ( e.g. Hash[9] => for month of September, I can display all appropriate values ). How can i get a unique key of type month, year which I can easily loop though to display all records grouped by Month and Year of creation.</p>
  
  <p>Thank you</p>
  
  <p><strong>EDIT</strong>:-</p>
  
  <p>I'm guessing one way to do this, is to make use the <code>created_at.to_date</code> api, provided <a href="http://api.rubyonrails.org/classes/Time.html" rel="noreferrer">here</a>
  . I only wonder, how I can <strong>strip out the day</strong> from <code>created_at.to_date</code> to get a <strong>unique</strong> month and year <strong>combination key</strong> which could <strong>work with the group_by function</strong>.</p>