Ruby on rails ActiveRecord::ReportsController中的UnknownAttributeError#导入未知属性'';卫报
我想导入监护人详细信息的excel。但当我选择excel导入时,它会给我错误信息 监护人的未知属性 这是我的代码: 卫报.rbRuby on rails ActiveRecord::ReportsController中的UnknownAttributeError#导入未知属性'';卫报,ruby-on-rails,ruby,Ruby On Rails,Ruby,我想导入监护人详细信息的excel。但当我选择excel导入时,它会给我错误信息 监护人的未知属性 这是我的代码: 卫报.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)
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
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>
导入
excel中的值为零,因此我在ReportsController中得到了一个错误,即为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"]`
你能把错误的全部信息都发出去吗?更容易看出错误的确切来源。还有一件事:我想表单标记中的url散列是不必要的。我在这一行得到了错误
record.attributes=row.to\u hash.slice(*row.to\u hash.keys)
你能检查一下row.to\u hash.slice(*row.to\u hash.keys)返回的是什么吗?问题可能出在::clean_for中,因此您可以尝试对其进行调试。[“名字”、“姓氏”、“关系”、“学生id”、“电子邮件”、“办公电话1”、“办公电话2”、“手机”、“办公地址1”、“无”、“办公地址2”、“城市”、“州”、“国家id”、“dob”、“职业”、“收入”、“教育”]
谢谢你的回答excel中的值为零,我调试了它并完成了。
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"]`