使用rails4的roo给出了未定义的方法`[]'为零:NilClass

时间:2014-10-30 15:33:34

标签: ruby-on-rails-4 roo-gem

我正在尝试使用基于http://railscasts.com/episodes/396-importing-csv-and-excel的Roo gem将CSV和Excel文件导入rails 4项目(带验证)。

我对Rails4而不是Rails3以及对Roo的更改进行了一些更改,我的ProjectImporter模型现在看起来像:

class ProductImport
  include ActiveModel::Model
  attr_accessor :file

  def initialize(attributes = {})
    attributes.each { |name, value| send("#{name}=", value) }
  end

  def persisted?
    false
  end

  def save
    if imported_products.map(&:valid?).all?
      imported_products.each(&:save!)
      true
    else
      imported_products.each_with_index do |product, index|
        product.errors.full_messages.each do |message|
          errors.add :base, "Row #{index + 2}: #{message}"
        end
      end
      false
    end
  end

  def imported_products
    @imported_products ||= load_imported_products
  end

  def load_imported_products
    spreadsheet = open_spreadsheet
    spreadsheet.default_sheet = spreadsheet.sheets.first
    puts "!!! Spreadsheet: #{spreadsheet}"
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = Product.find_by(id: row['id']) || Product.new
      product.attributes = row.to_hash.slice(*['name', 'released_on', 'price'])
      product
    end
  end

  def open_spreadsheet
    case File.extname(file.original_filename)
      when ".csv" then
        Roo::CSV.new(file.path, nil)
      when '.tsv' then
        Roo::CSV.new(file.path, csv_options: { col_sep: "\t" })
      when '.xls' then
        Roo::Excel.new(file.path, nil, :ignore)
      when '.xlsx' then
        Roo::Excelx.new(file.path, nil, :ignore)
      when '.ods' then
        Roo::OpenOffice.new(file.path, nil, :ignore)
      else
        raise "Unknown file type #{file.original_filename}"
    end
  end
end

当我尝试运行导入(使用测试CSV数据)时,header = spreadsheet.row(1)上的错误导致错误undefined method '[]' for nil:NilClass。我收录的额外puts声明确认spreadsheet本身不是零:它给出了!!! Spreadsheet: #<Roo::CSV:0x44c2c98>。但是,如果我尝试调用几乎任何预期的方法,例如#last_row,它会给我相同的未定义方法错误。

那么我做错了什么?

1 个答案:

答案 0 :(得分:7)

我遇到了同样的问题,这似乎是关于文件enconding的一个问题,我使用了这段代码并且修复了它。

def open_spreadsheet
    case File.extname(file.original_filename)
        when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "iso-8859-1:utf-8"})
        when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
        when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
        else raise "Unknown file type: #{file.original_filename}"           
    end 
end

我希望对你有帮助。