Demian Sims
Demian Sims

Reputation: 921

Getting 'undefined method `view_paths=' for #<ActionView::LookupContext:0x00007fdb191d6cc0> Did you mean? view_paths' error using PDFKit in Rails

I'm using PDFKit (along with the Gem render_anywhere and wkhtmltopdf-binary) to create a button for creating PDF's from HTML in Rails. I've followed a couple tutorials that both use 'invoices' as an example. My app uses 'audits'. I thought I'd followed everything to the tee but getting an error on the ActionView::LookupContext object: undefined method 'view_paths=' for #<ActionView::LookupContext:0x00007fdb191d6cc0> Did you mean? view_path. It has something to do with the wrong path and using a service class in Rails but can't seem to find a solution. Here's my code to make the PDF:

The PDFKit Gem: https://github.com/pdfkit/pdfkit

The tutorial I'm using: https://code.tutsplus.com/tutorials/generating-pdfs-from-html-with-rails--cms-22918

The downloads_controller:

class DownloadsController < ApplicationController


   def show
    respond_to do |format|
      format.pdf { send_audit_pdf }
    end
  end

  private

  def audit_pdf
    audit = params[:incoming]
    AuditPdf.new(audit)
  end

  def send_audit_pdf
    send_file audit_pdf.to_pdf,
      filename: audit_pdf.filename,
      type: "application/pdf",
      disposition: "inline"
  end

end

The Download Model:

require "render_anywhere"

class Download 
  include RenderAnywhere

  def initialize(audit)
    @audit = audit
  end

  def to_pdf
    kit = PDFKit.new(as_html, page_size: 'A4')
    kit.to_file("#{Rails.root}/public/audit.pdf")
  end

  def filename
    "audit #{audit.id}.pdf"
  end

  private

    attr_reader :audit

    def as_html
      render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
    end
end



My views/layout/audit_pdf.html.erb looks like this:

<!DOCTYPE html>
<html>
<head>
  <title>Audit PDF</title>
  <style>
    <%= Rails.application.assets.find_asset('audit.pdf').to_s %>
  </style>
</head>
<body>
  <%= yield %>
</body>
</html>

Upvotes: 1

Views: 1889

Answers (1)

the_ganesh_hegde
the_ganesh_hegde

Reputation: 61

Since you are using rails api only, you are facing this issue.

You need to change

def as_html
  render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
end

to:

def pdf_html
  ActionController::Base.new.render_to_string(template: 'audits/pdf.html.erb', layout: 'audit_pdf.erb')
end

Upvotes: 3

Related Questions