gpt4 book ai didi

ruby-on-rails - 如何使用MongoDB中的ActionController::Live下载CSV数据?

转载 作者:行者123 更新时间:2023-12-04 04:40:32 25 4
gpt4 key购买 nike

我已经在像这样的 Controller 中创建了CSV下载器

format.csv do
@records = Model.all

headers['Content-Disposition'] = "attachment; filename=\"products.csv\""
headers['Content-Type'] ||= 'text/csv'
end

现在,我想创建 server sent events来从中下载CSV文件,以进行优化。我知道我可以使用 ActionController::Live在Rails中完成此操作,但是我对此没有经验。

有人可以向我解释
  • 批量查询记录
  • 将记录添加到stream
  • 从浏览器一侧处理sse
  • 将记录写入CSV文件

  • 如果我的任何假设是错误的,请纠正我。帮助我以更好的方式做到这一点。谢谢。

    最佳答案

    Mongoid自动批量查询您的记录(有关更多信息,请访问here)

    要将记录添加到CSV文件,您应该执行以下操作:

    records = MyModel.all
    # By default batch_size is 100, but you can modify it using .batch_size(x)

    result = CSV.generate do |csv|
    csv << ["attribute1", "attribute2", ...]
    records.each do |r|
    csv << [r.attribute1, r.attribute2, ...]
    end
    end

    send_data result, filename: 'MyCsv.csv'

    记住 send_data 是一个ActionController方法!

    关于ruby-on-rails - 如何使用MongoDB中的ActionController::Live下载CSV数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265466/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com