2

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

ディレクトリにファイルを作成してからダウンロードします。ファイルを作成したくありません。

4

2 に答える 2

3

解決済み

  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ファイルを生成します

于 2012-08-13T12:22:51.913 に答える
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
于 2012-08-13T11:32:17.047 に答える