更智能的CSV和resque会导致未定义的方法关闭



我正在尝试使用Resque和SmarterCSV,但一直看到相同的错误:

undefined method 'close' for nil:NilClass

在我的日志中。 我不确定为什么会发生这种情况。 我做了一些挖掘,看到这个的人发现它与文件位置错误有关,但我只是将文件作为参数传递,它没有保存在任何地方。

我的表格:

<%= form_tag check_upload_file_path, multipart: true do %>
    <%= file_field_tag :file %>
    <%= select_tag 'location', options_from_collection_for_select(Location.real, 'id', 'name'), include_blank: true %>
    <br>
    <%= submit_tag "Preview", class: "btn btn-awaken btn-sm approve-me", name: 'preview' %>
<% end %>

我的控制器:

def check_upload_file
    Resque.enqueue(AddClientsFromScale, params[:file], params[:location])
    redirect_to bulk_uploads_path
end

我的工作人员:

class AddClientsFromScale
    @queue = :validate_file
    puts "adding clients from scale..."
    def self.perform(file, location_id)
        p file, location_id
        WeighIn.check_file(file, location_id)
    end
end

我的模型:

class WeighIn < ActiveRecord::Base
    @hash_for_new_clients = {
        ' ID'                           => 'scale_id',
        'Full Name'                     => 'name',
    }
    def self.check_file(file, location_id)
        options = {:key_mapping => @hash_for_new_clients, :strings_as_keys => true, :keep_original_headers => true, :remove_unmapped_keys => true}
        # prints the file and contents properly
        p "file: ", file["tempfile"] 
        SmarterCSV.process(file, options) do |row|
            p row
        end
    end
end

有人知道发生了什么吗?

问题是file变量是一个哈希,包含的数据不仅仅是文件本身。线索是你在哪里打印它 file["tempfile"] .这就是您需要插入 SmarterCSV 的内容,因为这是引用您尝试处理的实际文件的内容。

SmarterCSV.process(file["tempfile"], options) do |row|

就我而言,我遇到了一个额外的文件编码问题,我从 SmarterCSV 收到此错误:

警告:您正在尝试处理 UTF-8 输入,但未使用"b:utf-8"选项打开输入。请参阅自述文件"关于文件编码的说明"。

这就是最终为我所做的:

f = File.open(file["tempfile"], "r:bom|utf-8")
SmarterCSV.process(f, options) do |row|
    ...