views:

165

answers:

1

I have a collection of records in my database that I want to print out to separate tables based on the record date.

So I already have the following (in Haml, fyi):

%table
  %tr
    %th Name
    %th Type
    %th Total Hits
  - for record in @records
    %tr{ :class => cycle('odd','even') }
      %td= record.name
      %td= record.target_type
      %td= record.outbound + record.detail + record.custom + record.dynamic

At the moment, it displays all my records in the same table. record.recorded_on contains the date for my records. I want to generate separate tables, like the one above, for each day that contains all the records for that day.

How would I do this?

+3  A: 

Assuming recorded_on is a date, and not a DateTime:

@records = Record.all.group_by(&:recorded_on)

If it is a DateTime:

@records = Record.all.group_by { |record| record.recorded_on.to_date }

Now @records contains some nested arrays. Stick your table haml above in a partial named _record_table.html.haml. Be sure to change @records to a local variable records so it can be swapped out for each partial render.

Now your haml template looks like this:

- @records.each do |records_for_one_day|
  = render :partial => 'render_table', :locals => { :records => records_for_one_day }
Squeegy
neezer
Maximiliano Guzman
Max is right. In the second example I put up there I had to use the longhand because I wanted to additionally process result a bit, which the shorthand version has no support for.
Squeegy