问题
I have two csv exports on the same view, both with different data. Currently it's just downloading the same data for both.
View
<%= link_to "Trials export", data_path(format: "csv") %>
<%= link_to "Results export", data_path(format: "csv") %>
Controller
respond_to do |format|
format.html
format.csv { send_data @trial_data.trials_export, filename: "trials_export.csv" }
format.csv { send_data @trial_data.results_export, filename: "results_export.csv" }
end
Model
def self.trials_export
csv << [ data goes in here all work fine ]
end
def self.results_export
csv << [ data goes in here all work fine ]
end
回答1:
inside your link_to you can add additional data / parameters for example format_data (variable name can be anything)
View
<%= link_to "Trials export", data_path(request.parameters.merge({:format => :csv, format_data: "trial"})) %>
<%= link_to "Results export", data_path(request.parameters.merge({:format => :csv, format_data: "result"})) %>
in your controller inside csv block you can split it with if / case command
Controller
respond_to do |format|
format.html
format.csv do
if (params[:format_data] == 'trial')
send_data @trial_data.trials_export, filename: "trials_export.csv"
elsif (params[:format_data] == 'result')
send_data @trial_data.results_export, filename: "results_export.csv"
end
end
end
来源:https://stackoverflow.com/questions/55291375/rails-export-multiple-csv-in-same-view