Search code examples
ruby-on-railsrubypdfiterationprawn

Prawn: How to iterate from a table inside an iteration in the header?


I pass 3 @course ID's to courses.pdf. Then Prawn generates a PDF of 3 pages - one course pr page.

The problem: currently it prints all @participants from all 3 courses in all 3 pages.

It should only print the @participants for the current course in a table.

I have spend several hours trying different methods, asked in Facebook groups and searched Stackoverflow + Google for solutions.

class CoursesToPrintPdf < Prawn::Document

    def initialize(courses, participations)
        @courses = courses
        @participations = participations
        header
    end

    def header
        @courses.order('day ASC').each do |course|

            text_box("#{course.course_day_pdf}",
            :align => :right)
            text "#{course.round.round_name_simple}"

            table deltakere_rows do
                self.header = true
            end
        end
    end

    def deltakere_rows
        [["ID", "Name"]] +
        @participations.map do |p|
            [p.participant.id, p.participant.full_name]
        end
    end

end

Solution

  • Does a partecipation contain a course reference? If so, it could be something like this

    def deltakere_rows(course)
      [["ID", "Name"]] +
        @participations.select do |p|
          p.course_id == course.id
        end.map do |p|
          [p.participant.id, p.participant.full_name]
        end
    end
    

    And pass the course to deltakere_rows

    table deltakere_rows(course) do
      self.header = true
    end
    

    This could be the idea with the info we have