As the title says, it ’s about how to specify the format with the link_to
method.
It's pretty easy, but I'll leave it as a reminder because the article didn't hit unexpectedly.
The output format The html file is rendered in html format, right? There are other json format, pdf, csv, etc.
This time I will try assuming PDF output
Just specify format as the argument of path!
slim file
= link_to 'Display name', xxx_path(format: :pdf)
If you want to specify another id or set a parameter, you can just go into the argument in the same way.
slim file
= link_to 'Display name', xxx_path(format: :pdf, id: @post, parameter_name: parameter_content)
In the controller, it is OK if you specify the format and describe the process In the case of pdf, I think that send_file is often used to display or download the file. If you write as follows, the PDF file will be opened on the browser by specifying the file name.
controller
class HogesController < ApplicationController
def show
respond_to do |format|
format.pdf do
send_file(pdf_path, filename: filename, disposition: 'inline')
end
end
end
private
def pdf_path
#Specify the save location of pdf
@post.pdf.path #← If you use carrierwave, it looks like this
end
def filename
#Specify the pdf file name
"#{@post.id}.pdf"
end
end
When you do rails routes, you can see (.: Format) in the URI pattern. This will be the URI when format is specified
For example, if the format is pdf like this time, the URL will be something like https://xxxxxx/xxx.pdf
.
It means that it will be added in the form of .format format
at the end depending on the format ~
Recommended Posts