流式CSV下载丢失的记录

时间:2014-02-10 18:34:24

标签: ruby-on-rails export-to-csv

在我的Rails 3.2.x应用程序中,我已按照此博客文章中的说明成功重新实现我的CSV下载以执行流式下载,因为我的先前方法已超时。

http://smsohan.com/blog/2013/05/09/genereating-and-streaming-potentially-large-csv-files-using-ruby-on-rails/

它主要起作用,除了生成的CSV文件经常缺少最近几天或有时数周的记录。

这是我的控制器......

def index
  respond_to do |format|
    format.csv { render_csv }
  end
end

def render_csv
  set_file_headers
  set_streaming_headers
  response.status = 200
  self.response_body = csv_lines
end

def set_file_headers
  file_name = "service_requests.csv"
  headers["Content-Type"] = "text/csv"
  headers["Content-disposition"] = "attachment; filename=\"#{file_name}\""
end


def set_streaming_headers
  headers['X-Accel-Buffering'] = 'no'
  headers["Cache-Control"] ||= "no-cache"
  headers.delete("Content-Length")
end

def csv_lines
  Enumerator.new do |y|
    y << ServiceRequest.csv_header.to_s
    ServiceRequest.find_in_batches(500){ |transaction| y << transaction.to_csv_row.to_s }
  end
end

模特:

def to_csv_row

 CSV::Row.new([],[
      created_at.to_s(:table_date),
      created_at.strftime('%A'),
      created_at.to_s(:time),
      user.name,
      user.email,
      ...
 end

def self.find_in_batches(batch_size, &block)
  includes(:service, :user, :salon, :appointment => { checkout: [], cancellation: [], no_show: [] }).find_each(batch_size: batch_size) do |transaction|
    yield transaction
  end
end

请注意,我只是尝试下载&lt; 1000条记录,但复杂的连接使前一种方法超时。

当然,如果我在本地恢复prod数据库的副本,它可以完美地运行。但是,尝试从Heroku下载几乎总会导致一组不完整的记录。

任何帮助表示赞赏!

0 个答案:

没有答案