Rails CSV导入无法正常运行

时间:2013-06-13 22:33:52

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

基本上,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文件:

  

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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