我正在创建一个投资组合跟踪器,并且有两个CSV-一个用于显示我的所有投资组合(在我的索引页面中),另一个用于显示特定的投资组合(在我的显示页面中)。这是两种方法:
def index
@portfolios = Portfolio.all
csv_options = {col_sep: ',', force_quotes: true, quote_char: '"' }
filepath = "app/views/portfolios/investments.csv"
CSV.open(filepath, "wb", csv_options) do |csv|
headers = ...
csv << headers
@portfolios.each { |portfolio| csv << portfolio }
end
respond_to do |format|
format.html
format.csv { send_data @portfolios.to_csv, filename: "investments_#{Date.today}.csv"}
end
end
def show
csv_options = {col_sep: ',', force_quotes: true, quote_char: '"' }
filepath = "app/views/portfolios/portfolio_#{@portfolio.name}.csv"
CSV.open(filepath, "wb", csv_options) do |csv|
headers = ...
csv << headers
@portfolio.transactions.each { |transaction| csv << transaction }
end
respond_to do |format|
format.html
format.csv { send_data Portfolio.to_csv, filename: "#{@portfolio.name}_#{Date.today}.csv"}
end
end
CSV文件生成正确,但是当我尝试在显示页面(例如portfolios/1.csv
)下载CSV时,下载的文件中的内容属于我的索引页面的CSV(即使该文件名称正确)。
非常感谢!