Search code examples
ruby-on-railspostgresqlprawnnomethoderror

NoMethodError using Prawn in Rails 4


I'm trying to create a PDF with Prawn, using data from a Postgres database. I created a class ReportPdf as shown below, but I am getting a NoMethodError when I try to call .map on @tables.

app/controllers/forms_controller.rb

class FormsController < ApplicationController

def index
    @tables = Table.all
end

def forms

end

def new
    @tables = Table.new

    respond_to do |format|
        format.html
        format.pdf do
            pdf = ReportPdf.new(@tables)
            send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
        end
    end
end

def create
    @tables = Table.new(tables_params)
    if @tables.save
        redirect_to root_path, notice: "Success"
    else
        redirect_to root_path, alert: "Fail"
    end
end

private
def tables_params
    params.require(:table).permit(:first_name, :middle_name, :last_name)
end

end

app/pdfs/report_pdf.rb

class ReportPdf < Prawn::Document

def initialize(user_data)
  super()
  @tables = user_data
  header
  text_content
  table_content
end

def header
  image "#{Rails.root}/app/assets/images/officestock.jpg", width: 530, height: 150
end

def text_content
y_position = cursor - 50
bounding_box([0, y_position], :width => 270, :height => 300) do
  text "TEXT", size: 15, style: :bold
  text "MORE TEXT"
end

bounding_box([300, y_position], :width => 270, :height => 300) do
  text "TEXT", size: 15, style: :bold
  text "MORE TEXT"
end

end

def table_content
  table product_rows do
    row(0).font_style = :bold
    self.header = true
    self.row_colors = ['DDDDDD', 'FFFFFF']
    self.column_widths = [40, 300, 200]
  end
end

def product_rows
  [['First', 'Middle', 'Last']] +
    @tables.map do |data|
      [data.first_name, data.middle_name, data.last_name]
    end
end
end 

At this point, I'm not sure what the issue is. It seems very simple to me, so I may be missing something obvious. I've also installed the prawn-table gem, and that did not solve the issue either.

Any help would be appreciated!


Solution

  • In the new action you are assigning:

    @tables = Table.new
    

    which is - I suppose - a single object, not responding to map.