Rails使用活动存储读取csv文件数据

Die*_*sco 9 csv ruby-on-rails rails-activestorage

我有这个课程,我正在使用主动存储

class MaterialsUpload < ApplicationRecord
  has_one_attached :csv_file
end
Run Code Online (Sandbox Code Playgroud)

这是附件

#<ActiveStorage::Attached::One:0x007ff1f0be9e90
 @dependent=:purge_later,
 @name="csv_file",
 @record=
  #<MaterialsUpload:0x007ff1f0c604f0
   id: 3,
   success: 0,
   errors_list: [],
   total: 0,
   created_at: Mon, 12 Feb 2018 14:43:35 UTC +00:00,
   updated_at: Mon, 12 Feb 2018 14:43:35 UTC +00:00>>
Run Code Online (Sandbox Code Playgroud)

有没有办法可以读取数据,所以我可以做这样的事情

string = materials_upload.csv_file.read
CSV.parse(csv_string, headers: true) do |row|
    # do something
end
Run Code Online (Sandbox Code Playgroud)

Geo*_*orn 15

使用download获得该文件的内容:

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end
Run Code Online (Sandbox Code Playgroud)

  • @ george-claghorn我需要使用CSV.foreach而不是CSV.parse(因为文件中的行太多),并且file.download似乎占用了太多内存。如何获得所需的文件路径?(我正在使用Amazon S3) (2认同)