title: Ruby grouping/sorting by attribute and count
body: <p>I have been struggling with this and after some searching, I haven't been able to find anything online. Users choose from several study session dates (their first choice is the one that is the most convenient for them) and I store their choices as Id's that correspond to the chosen dates. The Id's are stored as an array for each user (ex: [1,3,2,4]). Each study session has a capacity, so what I need to do is sort it by their first choice but if their first choice is over the capacity, I need to place them into their second choice. So far, I have the grouping by first choice done but I don't know how to place all users who are over the capacity into their second choice. Here is my code so far:</p>
  
  <pre><code>&lt;% @choices.all.group_by { |choice| choice.choice.first}.each do |date, choices| %&gt;
    &lt;%= @options.where(:id =&gt; "#{date}").first.date.strftime('%B %d, %Y') %&gt; 
    at 
    &lt;%= @options.where(:id =&gt; "#{date}").first.time.strftime('%l:%M %P') %&gt;
    &lt;ul&gt;
    &lt;% choices.each do |sort| %&gt;
      &lt;li&gt;&lt;%= sort.name %&gt;&lt;/li&gt;
    &lt;% end %&gt;
    &lt;/ul&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>Thanks for your help!</p>