Search code examples
ruby-on-railstemplatespdflink-towicked-pdf

Controller action is missing templates while using wicked_pdf


I am using wicked_pdf for creating a pdf with database content.

First, I create a user and forward to a page looking like this:

<%= @user.name %>
<%= link_to 'Create PDF', pdf_pages_path(:user_id => @user.id) %>

My controller code:

class PdfPagesController < ApplicationController
  def show
    @user = User.find(params[:user_id])

    respond_to do |format|
      format.html
      format.pdf do
        render pdf: 'file_name'   
      end
    end
  end
end

My route file:

Rails.application.routes.draw do
   root 'landing#index'
   get 'pdf_pages', :to => 'pdf_pages#show'
   get 'users/new'
   resources :users
end

show.pdf.erb:

<h1>Hello World</h1>

When I try to open show.pdf.erb I get this error:

PdfPagesController#show is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

  • If I use link_to without variable passing I get the same error.

  • If I remove @user = User.find(params[:user_id]) from the controller, replace the link_to helper with a html href attribute and add get 'pdf_pages/show' to routes.rb everything works fine.

What am I doing wrong?


Solution

  • By default controllers consider all requests as HTML. You need to specify the format you're requesting if it's something else:

    <%= link_to 'Create PDF', pdf_pages_path(:user_id => @user.id, format: :pdf) %>
    

    Alternatively, if you're only ever going to request PDF on this action, you can specify it in the route:

    get 'pdf_pages', :to => 'pdf_pages#show', format: 'pdf'
    

    Then you don't need to specify it in link_to.