我正在使用带有ruby 1.8.7的rails 2.3.14,我想下载一个csv文件而不将其写入任何目录。
我的代码:
def export
@news = News.find(:all, :conditions => ["updated_at >= ? and news_source_id != 1 and ready = 1", 1.week.ago])
file_name = "Non_linksv_news_#{1.week.ago.strftime('%b-%d-%Y')}_to_#{Time.now.strftime('%b-%d-%Y')}.csv"
File.open(file_name, "w") do |file|
file_name << %w(Source Headline).to_csv
@news.each { |news| file_name << [news.news_source.name, news.news_headline].to_csv }
end
send_file file_name
end
它在目录中创建一个文件然后下载。我不想创建文件。
答案 0 :(得分:2)
我们使用这种方法
def export
output = [["Source", "Headline"]]
@news.each do |a_new|
output << [a_new,news_source.name.to_s, a_new.news_headline.to_s]
end
respond_to do |format|
format.csv {
send_data output.to_csv, :type => "text/csv", :filename => "My news csv.csv"
}
end
end
答案 1 :(得分:1)
解决
def export
ns = NewsSource.find_by_name 'Linksv', :select => :id
@news = News.find(:all, :conditions => ["updated_at >= ? and news_source_id != ? and ready = 1", 1.week.ago, ns.id])
file_name = "linksv_news_#{1.week.ago.strftime('%b-%d-%Y')}_to_#{Time.now.strftime('%b-%d-%Y')}.csv"
csv = %w(Source Headline).to_csv
@news.each { |news| csv << [news.news_source.name, news.news_headline].to_csv }
send_data csv, :filename => file_name, :type => "text/csv"
end
它将以适当的方式生成csv文件,包含行和列