Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby on rails how to download csv file using javascript

Some clarifications first.

I'm trying everything on local development environment.

In my UsersController I have a summary_csv method that builds a csv file and stores it in the /tmp/your-csv-file.csv location .

Once the system checks that the file is ready for download, I have a summary_csv.js.erb file that runs some javascript to help the user download the file, specifically, in summary_csv.js.erb, I try to do window.location="/users/download_csv"; and there is a download_csv method in the Users controller.

So I want the download to happen, but not sure about 2 things:

  1. How should I configure routes.rb for this download_csv method so that the download happens without throwing some kind of 'missing views' error? (at this point I don't care whether user has to directed to another view or can stay on the same page).

  2. What should go into the body of download_csv method so that window.location="/users/download_csv"; will initiate the download, for the file located at /tmp/your-csv-file.csv?

like image 468
namesake22 Avatar asked Sep 11 '26 22:09

namesake22


1 Answers

1) Put a get method inside users resource and collections like this

resources :users do
  collection do
    get 'download_csv'
  end
end

2) You just need to send_file, passing your file path to it, since it's ready.

Result

def download_csv
  send_file(
    "/tmp/your-csv-file.csv",
    filename: "your_custom_file_name.csv",
    type: "text/csv"
  )
end
like image 107
Ramon Marques Avatar answered Sep 14 '26 12:09

Ramon Marques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!