9

I need to add a link to download the file from assets/docs/Физика.pdf I do not know how to do that. I am trying to do so here: in view -

<%= link_to "download", '/Физика.pdf', :download => 'filename' %>

I get an error message:

No route matches [GET] "/%D0%A4%D0%B8%D0%B7%D0%B8%D0%BA%D0%B0.pdf"

What am I doing wrong? Help me please

Stiven Frams
  • 117
  • 1
  • 2
  • 7

8 Answers8

9

You can do steps as below:

Step1: Open file routes.rb

get 'download_pdf', to: "homes#download_pdf"

Step2: I assumed your controller was home_controller.rb, you put this line:

def download_pdf
  send_file "#{Rails.root}/app/assets/docs/Физика.pdf", type: "application/pdf", x_sendfile: true
end

Step3: In your view file.

<%= link_to "download", download_pdf_path %>

I suggest that you should put this docs folder in public folder.

For example: public/docs/*.pdf

Khanh Pham
  • 2,848
  • 2
  • 28
  • 36
5

step 1: The View

<%= link_to "download", download_path, target: "_blank"%>

step 2: Routing

match 'download', to: 'home#download', as: 'download', via: :get

step 3: Inside controller

send_file 'public/pdf/user.png', type: 'image/png', status: 202
vidur punj
  • 5,019
  • 4
  • 46
  • 65
2

When placing files in /assets you can use the Rails helper #asset_path.

<%= link_to 'download', asset_path('/docs/Физика.pdf') %>

source: http://guides.rubyonrails.org/asset_pipeline.html#asset-organization

HarlemSquirrel
  • 8,966
  • 5
  • 34
  • 34
2

Oddly enough, using the HTML download attribute in your link_to helper does the trick

<%= link_to "Download", file.file(:original, false), download:true %>

Hope this helps in the future!

Juan Pablo Ugas
  • 1,085
  • 9
  • 22
1

Try this:

<%= link_to 'download', root_path << '/assets/docs/Физика.pdf' %>
Hasmukh Rathod
  • 1,108
  • 1
  • 14
  • 20
0

The documentation indicates how build a download link to attachment file, would be like this

<a href="<%= user.avatar.attached? ? rails_blob_path(user.avatar, disposition: 'attachment') : '#' %>" target="_blank" download>Link</a>
Nico JL
  • 409
  • 3
  • 6
0

What works for me and also was the easiest:

= link_to "Click to download", asset_path("logo.png"), download: true
0

Rails 6 solution:

Step 1: Create your download route in your routes.rb file:

get 'download_pdf', to: "homes#download_pdf"

Step 2: Add the link to your views:

<%= link_to "download", download_single_path(url: 'url', file_name: 'filename') %>

Step 3: Add the action in your Controller homes_controller.rb where you take the params that you pass in your link_to:

def download_pdf
  require 'open-uri'
  url = params[:url]
  file_name = params[file_name]
  data = open(url).read
  send_data data, :disposition => 'attachment', :filename=>"#{file_name}.pdf"
end
Olivier Girardot
  • 389
  • 4
  • 16