我有一个应用程序,我想在其上提供从 CSV 和 Excel 文件格式导入记录的功能。我正在使用 roo gem,但在导入时它给出了错误“nil:NilClass 的未定义方法 `[]'”。
这是代码:
学生.rb:
require 'roo'
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]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
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
学生控制器.rb:
def import
Student.import(params[:file])
redirect_to students_path, notice: "Record imported Successfully."
end
新的.html.erb:
<%= form_tag import_students_path, multipart: true do %>
<%= file_field_tag :file , :required=> true%> <br/>
<%= submit_tag "Import" , :class => "btn btn-primary btn-block" %>
<% end %>
告诉我我做错了什么?