Ruby on rails 在RubyonRails中使用RooGem导入.xlsx文件时出错
我得到了以下错误:Ruby on rails 在RubyonRails中使用RooGem导入.xlsx文件时出错,ruby-on-rails,ruby,excel,Ruby On Rails,Ruby,Excel,我得到了以下错误: NoMethodError in ClientsController#table undefined method `phone' for nil:NilClass 当我尝试将.xlsx、.xls或.csv文件导入RubyonRails应用程序时,就会发生这种情况 型号代码如下所示: attr_accessible :name, :kind, :address_attributes, :emails_attributes, :phones_attributes, :atta
NoMethodError in ClientsController#table
undefined method `phone' for nil:NilClass
当我尝试将.xlsx、.xls或.csv文件导入RubyonRails应用程序时,就会发生这种情况
型号代码如下所示:
attr_accessible :name, :kind, :address_attributes, :emails_attributes, :phones_attributes, :attachments_attributes
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
client = find_by_id(row["id"]) || new
client.attributes = row.to_hash.slice(*accessible_attributes)
client.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when '.csv' then Roo::Csv.new(file.path)
when '.xls' then Roo::Excel.new(file.path)
when '.xlsx' then Roo::Excelx.new(file.path)
else
raise "Unknown file type: #{file.original_filename}"
end
end
def import
Client.import(params[:file])
redirect_to clients_path, notice: "Clients imported."
end
控制器代码如下所示:
attr_accessible :name, :kind, :address_attributes, :emails_attributes, :phones_attributes, :attachments_attributes
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
client = find_by_id(row["id"]) || new
client.attributes = row.to_hash.slice(*accessible_attributes)
client.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when '.csv' then Roo::Csv.new(file.path)
when '.xls' then Roo::Excel.new(file.path)
when '.xlsx' then Roo::Excelx.new(file.path)
else
raise "Unknown file type: #{file.original_filename}"
end
end
def import
Client.import(params[:file])
redirect_to clients_path, notice: "Clients imported."
end
apps/Services/config/application.rb文件包括以下代码:
require 'csv'
require 'iconv'
gem文件包括以下内容:
gem 'roo', '~> 2.1.0'
gem "iconv", "~> 1.0.3"
gem 'roo-xls'
我认为您应该对Roogem使用以下语法:
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path, nil, :ignore)
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
我应用了你的建议@marwen。它不工作:ClientsController中的RuntimeError#导入未知文件类型:client1.xl您是否使用
carrier\u wave
进行文件上载?是的,我正在使用carrier\u wave进行文件上载我应用了您的修改。它不工作,出现以下错误:未定义#的“file”方法,这表明此处未使用载波。我们将返回到您以前的代码,并进一步研究它。