将excel数据导入rails

时间:2016-10-27 06:40:30

标签: ruby-on-rails excel

我正在搜索导入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

感谢。

1 个答案:

答案 0 :(得分:0)

在ruby常量中以大写字符开头。您必须写subject而不是Subject。在你的情况下,ruby将Subject视为常量并抱怨改变常量。