Question

I'm using wicked_pdf gem to generate a pdf file:

I want to generate the pdf only if the object is persisted/saved in database:

Something like this:

def new
  @invoice = Invoice.new
  respond_to do |format|
    format.html # new.html.erb
  end
end

def create
  @invoice = Invoice.new(invoice_params)
  respond_to do |format|
    if @invoice.save
      format.html { redirect_to invoice_path(@invoice), notice: "Yesss!") }
    else
      format.html { render action: new, :alert => "Oops :(" }
    end
    format.pdf do
      @example_text = "exampletext"
        render :pdf => "file_name",
               :template => 'path/to/template'
    end
  end
end

But with this code only respond to html. I want generate the pdf inside of:

if @invoice.save
  #generate the pdf here
  format.html { redirect_to invoice_path(@invoice), notice: "Yesss!") }
else

How can I do it, Can I use a callback?

Was it helpful?

Solution

Remove the respond_to block like so:

def create
...
  if @invoice.save
   render :pdf=>"file_name",
   :template=>'/path/to/template'
  else
    render action: "new", :alert=>"Oops :("
  end
 end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top