gpt4 book ai didi

ruby-on-rails-4 - 带有 rails4 的 Roo 为 nil :NilClass 提供未定义的方法 `[]'

转载 作者:行者123 更新时间:2023-12-04 20:52:23 24 4
gpt4 key购买 nike

我正在尝试使用基于 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 ,它给了我同样的未定义方法错误。

那我做错了什么?

最佳答案

我有同样的问题,似乎是关于文件编码的问题,我使用了这段代码并且它被修复了。

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

希望对你有所帮助。

关于ruby-on-rails-4 - 带有 rails4 的 Roo 为 nil :NilClass 提供未定义的方法 `[]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com