ruby-on-railsrubyruby-on-rails-5ruby-on-rails-6prawn

Prawn-table: Iterating Through Active Record Relation Object to fill in Content


I am using the ruby gem: prawn and the extension prawn-table to provide prawn the functionality of creating tables.

The basics of creating a table with prawn displayed here is straight forward when you have static data:

# This works.  Easy because it is static data
def prepare_for_print
  pdf = Prawn::Document.new
  pdf.font_size 11
  pdf.font "Times-Roman"

  pdf.table([ ["short", "short", "loooooooooooooooooooong "*30],
              ["short", "loooooooooooooooooooong "*15, "short"],
              ["loooooooooooooooooooong "*10, "short", "short"] ])
  return pdf
end

Great. That wasn't bad. But now I want to iterate through an active record relation object, but my attempt is just not working:

def prepare_for_print
  pdf = Prawn::Document.new
  pdf.font_size 11
  pdf.font "Times-Roman"


  calls_by_disability.each do |disability|
    pdf.text "#{disability}", style: :bold, color: "001133"
    pdf.table([ ["Call ID", "Date", "County", "Service Category", "Service", "Notes"],
              disability.calls.each do |call|
                ["hello", "world", "foo", "bar", "bazz", "adsfsa"],
              end
              ])
  end
  return pdf
end

The issue is with iterating through the associated calls:

disability.calls.each do |call|
  ["hello", "world", "foo", "bar", "bazz", "adsfsa"],
end

Any tips are appreciated. Thanks!


Solution

  •   calls_by_disability.each do |disability|
        pdf.text "#{disability}", style: :bold, color: "001133"
    
        header = ["Call ID", "Date", "County", "Service Category", "Service", "Notes"]
        table_data = []
        table_data << header
        disability.calls.map do |call|
          table_data << [call.id, call.date, call.country, call.service_category, call_service, call.notes]
        end
        pdf.table(table_data)
      end