Rails アクティブストレージでcsvファイルデータを読み込む 質問する

Rails アクティブストレージでcsvファイルデータを読み込む 質問する

私はこのクラスを持っており、アクティブストレージを使用しています

class MaterialsUpload < ApplicationRecord
  has_one_attached :csv_file
end

これは添付ファイルです

#<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>>

このようなことができるようにデータを読み取る方法はありますか?

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

ベストアンサー1

使用downloadファイルの内容を取得するには:

CSV.parse(materials_upload.csv_file.download, headers: true) do |row|
  # ...
end

おすすめ記事