I have the following code in my Rails 3 application:
Show view (from another model called animal.rb)
<% @animal.labs.each do |lab| %>
<li>
<%= lab.TestDone.strftime("%d %b. %Y") %>
<h5><%= lab.TestType %></h5>
<h6><%= lab.TestLower %></h6>
<b><%= lab.TestResult %></b>
<h6><%= lab.TestUpper %></h6>
</li>
<% end %>
lab model
belongs_to :animal
default_scope :order => "TestDone DESC", :group => "TestDone"
The above code successfully group all results by date. However, it only shows the first of each value after the date.
For example, if the output was originally (before the grouping) like this:
<li>
26 April 2012
<h5>Glucose</h5>
<h6>1.0</h6>
<b>1.8</b>
<h6>2.0</h6>
</li>
<li>
26 April 2012
<h5>WBC</h5>
<h6>1.1</h6>
<b>2.8</b>
<h6>3.0</h6>
</li>
<li>
26 April 2012
<h5>ABC</h5>
<h6>1.0</h6>
<b>1.6</b>
<h6>2.0</h6>
</li>
then it would output the following after the grouping:
<li>
26 April 2012
<h5>Glucose</h5>
<h6>1.0</h6>
<b>1.8</b>
<h6>2.0</h6>
</li>
What is the correct way of producing something like this:
<li>26 April 2012</li>
<li>
<h5>Glucose</h5>
<h6>1.0</h6>
<b>1.8</b>
<h6>2.0</h6>
</li>
<li>
<h5>WBC</h5>
<h6>1.1</h6>
<b>2.8</b>
<h6>3.0</h6>
</li>
<li>
<h5>ABC</h5>
<h6>1.0</h6>
<b>1.6</b>
<h6>2.0</h6>
</li>
So I have a date heading and then every record with that date is listed below?
A simpler way would be to use group_by
like so:
<% @animal.labs.group_by{|l| l.TestDone.strftime("%d %b. %Y") }.each do |testdate,labs| %>
<li><%= testdate %></li>
<% labs.each do |lab| %>
<li>
<h5><%= lab.TestType %></h5>
<h6><%= lab.TestLower %></h6>
<b><%= lab.TestResult %></b>
<h6><%= lab.TestUpper %></h6>
</li>
<% end %>
<% end %>
http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by