Ruby on rails 4 带有rails4的Roo给出了未定义的方法“[]';零级:零级
我正在尝试使用RooGem将CSV和Excel文件导入Rails4项目(带有验证),基于 我对Rails4而不是Rails3进行了一些更改,并对Roo进行了一些更改,我的ProjectImporter模型现在看起来如下所示:Ruby on rails 4 带有rails4的Roo给出了未定义的方法“[]';零级:零级,ruby-on-rails-4,roo-gem,Ruby On Rails 4,Roo Gem,我正在尝试使用RooGem将CSV和Excel文件导入Rails4项目(带有验证),基于 我对Rails4而不是Rails3进行了一些更改,并对Roo进行了一些更改,我的ProjectImporter模型现在看起来如下所示: class ProductImport include ActiveModel::Model attr_accessor :file def initialize(attributes = {}) attributes.each { |name, va
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)
上失败,错误为未定义nil:NilClass的方法“[]”。我包含的额外的puts
语句确认了电子表格
本身不是零:它给出了!!!电子表格:#
。但是,如果我尝试调用它上几乎任何预期的方法,例如#last_row
,它会给我相同的未定义方法错误
那么我做错了什么呢?我也有同样的问题,似乎是关于文件编码的问题,我使用了这段代码,它被修复了
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
我希望这对您有所帮助。它可能会准确地告诉您发生了NilClass
错误的行。请提供。我已经提供了。正如我所写,“它在header=spreadsheet.row(1)
上失败”。这是load\u imported\u products
的第四行,在调试put
之后,我立即插入电子表格检查是否为nil
。第(1)行不是方法[]
。当出现错误时,我要求提供完整的调用堆栈<代码>[]
可能来自Roo内部-您应该在调用堆栈中看到一行引用该代码.row(1)
只是触发错误的失败API调用。在指定之前,默认编码是什么?