![](/img/trans.png)
[英]Rails - how to create file (XML) and save it into Amazon S3 bucket?
[英]How to export active record data to excel file and save xlsx file into Amazon S3 bucket without storing it on local machine using ruby on rails
在我們的 rails 6 項目中,我想將活動記錄數據導出到 excel 文件並將 xls 文件保存到 S3 存儲桶中,而不將 xls 數據存儲在本地數據庫上,並將文件鏈接發送到 email 並提供從 Z0C83F57C786A0B7EBAZ93 下載 xls 功能。 請幫我。
# app/models/csv_export.rb
class CsvExport < ApplicationRecord
has_one_attached :file
# ...
end
將 ActiveStorage 配置為使用 S3 作為提供程序。 請參閱https://medium.com/alturasoluciones/setting-up-rails-5-active-storage-with-amazon-s3-3d158cf021ff
# app/jobs/csv_export_job.rb
require 'csv'
class CsvExportJob < ApplicationJob
queue_as :default
def perform(csv_export_id)
csv_export = CsvExport.find_by(id: csv_export_id)
csv_export.file.attach \
io: StringIO.new(csv_string), # add csv_string call here
filename: filename
# ...
end
private
# ...
CSV_COLUMNS = %w[id name email].freeze
def csv_string
CSV.generate(headers: true) do |csv|
csv << CSV_COLUMNS
# or whatever data you want to export
User.all.each do |contact|
csv << CSV_COLUMNS.map { |col| contact.send(col) }
end
end
end
end
例如來自 controller 動作
csv_export = CsvExport.create(status: :started)
CsvExportJob.perform_later csv_export.id
我希望這些例子能給你帶來正確的方向。 如果您需要詳細幫助,可以查看這篇文章https://railsbyexample.com/export-records-to-csv-files-using-activestorage/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.