简体   繁体   中英

Calling a specific respond_to block method

I am trying to format a link_to tag in order to generate a pdf file (wicked_pdf gem) with the following respond_to block:

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

I have already created blocks with javascript method. But it was then fairly easy to get the JS rendered : only add remote: true to my form.

In case of other mime types or respond_to block methods, I have no clue how to write my link_to tag to let the controller know I want a specific method against another...

One of the ways that the respond_to block determines which format to render is by looking at the extension of the url. For instance, if I have in my routes:

Rails.application.routes.draw do
  get 'home/index', as: 'home'
end

and then in my controller:

class HomeController < ApplicationController
  def index
    respond_to do |format|
      format.html { render inline: 'HTML' }
      format.pdf { render inline: 'PDF' }
    end
  end
end

I can get the format.pdf by using a .pdf extension:

$ curl http://localhost:3000/home/index.pdf
# PDF
$ curl http://localhost:3000/home/index.html
# HTML

When creating a link_to , you can tell it which extension to use by passing it into the url_for (or whichever named route helper you're using):

<%= link_to 'View the PDF', url_for(controller: 'home', action: 'index', format: 'pdf') %>
# => <a href="/home/index.pdf">View the PDF</a>
<%= link_to 'View the PDF', home_path(format: 'pdf') %>
# => <a href="/home/index.pdf">View the PDF</a>

The way I believe remote: true works is by setting the Accept header. which Rails also uses to figure out what respond_to item to call:

$ curl -H 'Accept: application/pdf' http://localhost:3000/home/index
# PDF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM