我正在搜索导入excel数据到mySQL数据库。我指的是“Ruby on Rails - Railscasts#396导入Csv和Excel”。跟着它,我得到了错误
dynamic constant assignment Subject = find_by(id: row["id"]) || new ^
任何人都可以解释并给出解决方案。我的代码是model.rb,
def self.import(file)
allowed_attributes = [ "module_number", "module_name"]
Spreadsheet.client_encoding = 'UTF-8'
spreadsheet = open_spreadsheet(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
subject = find_by(id: row["id"]) || new
subject.attributes = row.to_hash.slice(*allowed_attributes)
subject.save!
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)
when ".xml" then
Roo::XML.new(file.path, nil, :ignore)
else
raise "Unknown file type: #{file.original_filename}"
end
端
感谢。
答案 0 :(得分:0)
在ruby常量中以大写字符开头。您必须写subject
而不是Subject
。在你的情况下,ruby将Subject
视为常量并抱怨改变常量。