我想导入学生记录,但是当我选择文件时,它会显示错误
NoMethodError in ReportsController#import
undefined method
original_filename' for" students.xlsx":String`
我尝试了这个,我得到了
[1] pry(#<ReportsController>)> Student.import(params[:file])
NoMethodError: undefined method
original_filename&#39; for&#34; import.xlsx&#34;:String
来自/home/dk/import_multiple/school/app/models/student.rb:283:in open_spreadsheet'
这是我的代码:
控制器
def importer
params[:role] == :guardian ? Guardian : Student
end
def import
importer.import(params[:file])
redirect_to import_reports_path, notice: "Students imported."
end
student.rb
COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"] # and so on
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]
row = clean_for row, COLUMNS_TO_STRING
record = Student.find_by(:id => row["id"],:batch_id => row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 => row["phone1"],:phone2 => row["phone2"]) || new
record.attributes = row.to_hash.slice(*row.to_hash.keys)
record.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
guardian.rb
COLUMNS_TO_STRING = ["student_id"] # and so on
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]
row = clean_for row, COLUMNS_TO_STRING
guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
guardian.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
查看
<h1>IMPORT</h1>
<div class = "well">
<p>
<%= form_tag import_reports_path do %>
<%= file_field_tag :file%>
<br>
<%= submit_tag "Import",class: "btn btn-primary" %>
<% end %>
</p>
</div>
答案 0 :(得分:1)
您的form_tag
需要知道其中有多部分文件上传字段 - 否则它将提交原始数据,而不是实际上传文件。
form_tag import_reports_path, multipart: true do
答案 1 :(得分:0)
看起来open_spreadsheet需要一个文件对象,而不是一个字符串