ruby-on-rails - 在 Rails 6 中读取存储在 Active Storage 中的 CSV 文件

标签 ruby-on-rails ruby csv rails-activestorage

我正在使用 Active Storage 上传 CSV 文件,然后读取这些文件以更新数据库中的值。我已经设置了一个基本的上传文件类来执行此操作;

class VendorFile < ApplicationRecord
    has_one_attached :vendor_upload_file
    validate :acceptable_file
end

我像这样使用 Rails 6 打开方法打开 CSV 文件;

self.vendor_upload_file.open do |file|
  CSV.foreach(file) do |row|
    do some processing....
  end
end

这对于处理整个文件非常有效。问题是在处理之前我想打开文件并阅读第一行以确保文件格式正确。如果文件存储在 Active Storage 中,我找不到打开文件并只读取第一行的方法。有谁知道这样做的方法吗? 谢谢!

最佳答案

怎么样?

headers = self.vendor_upload_file.open(&:first).parse_csv

关于ruby-on-rails - 在 Rails 6 中读取存储在 Active Storage 中的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62076872/

相关文章:

ruby-on-rails - Rails:如何像在 Django 中一样使用 ActiveRecord::Schema 创建数据库模式?

ruby-on-rails - rails : create scaffold for models to inherit from superclass?

ruby-on-rails - ActiveRecord::StatementInvalid: PG::UndefinedTable: 错误: 关系 "users"不存在

python - 'utf- 8' codec can' t 解码字节 0xa0 在位置 4276 : invalid start byte

php - 使用 PHP 将 MySQL 列导出到 CSV

ruby-on-rails - spree commerce如何兑换订购的商品?

ruby - 获取全局变量指向的当前值

jquery - Rails jquery 适用于本地主机,但不适用于 heroku

ruby-on-rails - neo4j.rb 检查两个节点之间是否已经存在关系

sql-server-2005 - 不使用 SSIS 将平面文件导入 SQL Server 2005 的最优雅方法