Rails export multiple csv in same view

百般思念 提交于 2021-02-10 05:22:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!