【问题标题】:Import excel data into database in rails将excel数据导入rails中的数据库
【发布时间】:2017-03-09 17:42:06
【问题描述】:

我正在搜索将 excel 数据导入 mySQL 数据库。我参考“Ruby on Rails - Railscasts #396 Importing Csv And 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

结束

谢谢。

【问题讨论】:

    标签: ruby-on-rails excel


    【解决方案1】:

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

    【讨论】:

    • 但它是一个型号名称。主题 = find_by(id: row["id"]) ||新的 Subject.attributes = row_to_hash Subject.create!
    • 谢谢。我现在才注意到。你的观点是正确的。我试试这个。很抱歉造成误解。
    • "没有这样的文件或目录@rb_sysopen - /tmp/oo_20161027-13123-106anlt/roo_workbook.xml" 现在我得到了这种类型的错误。我不理解那个错误
    • rb_sysopen 是一个新错误。此错误必须在您的代码中的其他地方出现。没有代码,我只能猜测出了什么问题。似乎roo 试图打开一个不退出的文件,或者您没有对/tmp 的写入权限
    • 我收到错误为“/tmp/RackMultipart20161101-6013-1duaki1.xls”的“未定义方法‘original_filename’:String”。这是什么类型的错误?是存储错误???
    猜你喜欢
    • 2011-06-24
    • 2016-02-09
    • 2020-02-27
    • 2017-07-05
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多