Tutorial :Rails: Generating Tables based on groups of related database records


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?


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 }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »