【问题标题】:Rails CSV import not functioning properlyRails CSV 导入无法正常工作
【发布时间】:2013-06-10 12:04:00
【问题描述】:

基本上,CSV 导入不起作用。

型号代码:

def self.import(file,admin_id)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    new_row = row.to_hash.merge(:merchant_id => admin_id)    
    Inventory.create! new_row 
  end
end

def self.open_spreadsheet(file)
require 'iconv'
    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)
        else raise "Unknown file type: #{file.original_filename}"
    end
end

控制器动作:

def import
  Inventory.import(params[:file],params[:admin_id])
  redirect_to :inventories, :notice => "Imported Successfully."
end

导入按钮,选择文件,一切正常。提交时:

    SyntaxError in InventoriesController#import

    (eval):2: syntax error, unexpected tIDENTIFIER, expecting ')'
                    read_key(:Parts name)
                                        ^
    (eval):6: syntax error, unexpected tIDENTIFIER, expecting ')'
                    read_key_before_type_cast(:Parts name)
                                                         ^
    (eval):10: syntax error, unexpected tIDENTIFIER, expecting ')'
                    write_key(:Parts name, value)
                                         ^
    (eval):10: syntax error, unexpected ')', expecting '='
    (eval):14: syntax error, unexpected tIDENTIFIER, expecting ')'
                    read_key(:Parts name).present?
                                        ^
    (eval):15: syntax error, unexpected $end, expecting keyword_end

有人可以解释一下吗?我什至找不到调试实际方法的好方法,以准确查看它试图做什么以及它是如何失败的。

在标题行中有一个类似这样的模板 CSV 文件:

零件名称零件 number 数量 成本 价格 税 位置 描述 可编辑

【问题讨论】:

  • 这似乎是 MongoMapper 中的一个错误,请尝试更新 gem。
  • 我没有看过 CSV 处理 gem,但它确实看起来像是假设 CSV 模板中的列名是有效的符号字符串,并且“零件名称”中存在空格并且“部件号”导致语法错误。
  • @Peter - 去掉空格让我们前进了一步。它仍然失败,但不再抱怨零件名称的东西。谢谢你。

标签: ruby-on-rails ruby mongodb csv import


【解决方案1】:

根据我的评论,语法错误是由于尝试将列名转换为符号而产生的,如果列名包含空格,这将不起作用。有问题的代码似乎在 https://github.com/jnunemaker/mongomapper/blob/f5f695215effea909df65304898f4512600baa08/lib/mongo_mapper/plugins/keys.rb 中,但我没有检查是否有与此相关的文档或问题。

【讨论】:

    【解决方案2】:

    答案原来是标题名称中的空格。我希望彼得能提交答案,以便我可以点击它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多