的方法之一是, respond_to
塊通過查看url的擴展名來確定呈現哪種格式。舉例來說,如果我有我的路線:
Rails.application.routes.draw do
get 'home/index', as: 'home'
end
,然後在我的控制器:
class HomeController < ApplicationController
def index
respond_to do |format|
format.html { render inline: 'HTML' }
format.pdf { render inline: 'PDF' }
end
end
end
我可以用一個.pdf
擴展獲得format.pdf
:
$ curl http://localhost:3000/home/index.pdf
# PDF
$ curl http://localhost:3000/home/index.html
# HTML
當創建一個link_to
,你可以通過將它傳遞給url_for
(或你使用的任何一個指定的路由幫助程序)來告訴它使用哪個擴展:
<%= 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>
的方式,我相信remote: true
作品是通過設置接受頭。哪些Rails還用來弄清楚什麼respond_to
項目要致電:
$ curl -H 'Accept: application/pdf' http://localhost:3000/home/index
# PDF
非常感謝你! '格式:'pdf''到我的路徑做了伎倆 – Maxence