Liz
Liz

Reputation: 1457

Download PDF in Rails Show Page with Different PDF per Show

I'm trying to add a PDF download link on a blog I've created and am having trouble with the linking.

I consulted several SO posts (like this and this) to get as far as I have, but seeing as I'm working off variables (because I'm on blogs#show they only got me so far.

In my form, I have @blog.link_text for the exact link text that should show on the page (e.g. "Download a Free Printable PDF for Your Notes") and @blog.link_filename to store the path of the PDF that should be downloaded.

On blogs#show I have the following link in ERB:

  <h3>
    <%= link_to download_pdf_path(@blog.link_filename), type: "application/pdf" do %>
      <%= @blog.link_text %>
    <% end %>
  </h3>

Then in my routes.rb I have this:

  get "download_pdf", to: "blogs#download_pdf"

Finally, in my blogs_controller.rb I have the download_pdf method:

  def download_pdf(filename)
    send_file filename, type: "application/pdf"
  end

I currently have "app/assets/images/house_tour_notes.pdf" as the @blog.link_filename value, but I've tried a variety of other values. I currently have a copy of the PDF in images and in public.

The link appears properly on the page, but when it's clicked, I get:

No route matches [GET] "/download_pdf.%22app%2Fassets%2Fimages%2Fhouse_tour_notes.pdf%22"

Can anyone help troubleshoot this? Where am I going wrong?

Upvotes: 1

Views: 164

Answers (1)

bo-oz
bo-oz

Reputation: 2872

I think you can fix this easily by approaching it differently. The link could go to the blogpost itself:

<h3>
  <%= link_to download_pdf_path(@blog), type: "application/pdf" do %>
    <%= @blog.link_text %>
  <% end %>
</h3>

Change the route:

get "blogs/:id/download_pdf", controller: 'blogs', action:'download_pdf', as: 'download_pdf'

Then change the controller:

def download_pdf
  @blog = Blog.find(params[:id])
  send_file Rails.root.join(@blog.filename), type: "application/pdf"
end

Upvotes: 1

Related Questions