ruby-on-railspdfjpegbutton-to

Multiple buttons pointing to single Controller Action


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.


Solution

  • 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.