Reputation: 357
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:
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).
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
?
Upvotes: 3
Views: 2083
Reputation: 357
I ended up finding out the solution. Thanks to all who offered help
So window.location
was the best method to use after all.
1) Set it to controller/method
.
2) send_file
appropriately in the body of the above method .
3) Set the correct routes in the right order.
Step 3 was critical to getting it work.
The route for controller/method
must be configured exactly to not make Rails confused as to where it should route your action.
resources :users do
collection do
get 'download_csv' => 'specify which controller#which_method_name'
end
end
Upvotes: 0
Reputation: 3264
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
Upvotes: 1