我想导入好的Guardian详细信息。但是当我选择excel导入它时会给我错误 未知属性''为卫报
这是我的代码:
guardian.rb
class Guardian < ActiveRecord::Base
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
record = Guardian.find_by(:student_id => row["student_id"]) || new
record.attributes = row.to_hash.slice(*row.to_hash.keys)
record.create!
end
end
def self.clean_for row_as_hash, string_columns_array
row_as_hash.each do |key, value|
if string_columns_array.include?key
row_as_hash[key] = value.to_i.to_s
end
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
end
report_controller.rb
def import
Guardian.import(params[:file])
redirect_to import_reports_path, notice: "Students imported."
end
import.html.erb
<h1>IMPORT</h1>
<div class = "well">
<p>
<%= form_tag import_reports_path,url:{action: 'import_excel',controller: 'reports'}, multipart: true do %>
<%= file_field_tag :file%>
<br>
<%= submit_tag "Import",class: "btn btn-primary" %>
<% end %>
</p>
</div>
答案 0 :(得分:0)
excel中的值是nil所以我得到一个错误,因为在ReportsController中的 ActiveRecord :: UnknownAttributeError#导入未知属性''为Guardian
Debugging solved my problem:
`pry(Guardian)> header = spreadsheet.row(1)
=> ["first_name",
"last_name",
"relation",
"student_id",
"email",
"office_phone1",
"office_phone2",
"mobile_phone",
"office_address_line1",
nil,
"office_address_line2",
"city",
"state",
"country_id",
"dob",
"occupation",
"income",
"education"]`