2

I am making an app where user can print a doc in either PDF or JPG format, using wicked-pdf and imgkit respectively. I have two buttons, one for PDF and other JPG. Is it possible to have these buttons point to same action in controller which here is 'create'. my buttons are as-

<%= button_to "Print Bill[PDF]", :action => "create" %>

<%= button_to "Print Bill[JPG]", :action => "new" %>

can i make both the actions create? if yes, how so? How to catch which button is hit and render the respective view.

victorkt
  • 13,992
  • 9
  • 52
  • 51
Niyanta
  • 473
  • 1
  • 9
  • 15

1 Answers1

1

First of all, it is generally recommended to use route helpers, rather than specify controllers and actions. So your code could be

<%= button_to "Print Bill[PDF]", bill_print_path(@bill, format: :pdf) %>
<%= button_to "Print Bill[JPG]", bill_print_path(@bill, format: :jpeg) %>

and in your controller

def print
    # insert here code to find your bill and load it from DB
    respond_to |format| do
        format.jpeg do
            # code to produce the jpeg version of the bill
        end
        format.pdf do
            # code to produce the pdf version of the bill
        end
    end
end

As a final step I would change button_to to link_to and style your link as a button, but that is more of a personal preference.

Marco Sandrini
  • 688
  • 4
  • 11
  • Just would like to add that in order for the PDF format to work you will have to add its mime type to the `config/initializers/mime_types.rb` file, eg: `Mime::Type.register "application/pdf", :pdf`. – victorkt Apr 12 '15 at 12:19
  • @victorkohl: very good point! I just assumed that the user already had the generation of PDF and JPEG sorted out, and was just looking for ways to consolidate it into a single controller method... – Marco Sandrini Apr 12 '15 at 12:22
  • The PDF format is working in itself, I am just taking care of making them both work via single action. – Niyanta Apr 12 '15 at 12:23