我正在尝试基于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
本身不是 nil:它给出了!!! Spreadsheet: #<Roo::CSV:0x44c2c98>
. 但是,如果我尝试在其上调用几乎任何预期的方法,例如#last_row
,它会给我同样的未定义方法错误。
那么我做错了什么?