0

我正在使用 roo 库解析一个 .xls 文件并填充我的模型。我为此和using rake db:seed命令使用了seeds.rb 文件。我收到一条错误消息,提示我尝试打开的文件不存在,但它位于 seed.rb 的同一文件夹中。这就是我到目前为止所得到的。

require 'rubygems'
require 'roo'
require 'active_record'

co = Roo::Excel.new("excel.xls")

co.default_sheet = co.sheets.first

2.upto(42700) do |line|
  #Category
  category_xls = co.cell(line, 'A')
  category_id = category_xls[0,2].to_i
  category_name = category_xls[4, category_xls.length]

  #Subcategory
  subcategory_xls = co.cell(line, 'B')

  #Item
  item_xls = co.cell(line, 'C')
  partno_xls = co.cell(line, 'D')
  description_xls = co.cell(line, 'E')
  explanation_xls = co.cell(line, 'H')
  information_xls = co.cell(line, 'J')

  #Uom
  uom_xls = co.cell(line, 'F')

  #MTML
  mtml_xls = co.cell(line, 'G')

  #Picture
  #picture = co.cell(line, 'I')

  # cria uma categoria e a insere no banco, caso ela nao exista
  category = Category.find_or_create_by_category_name(category_number: category_id, category_name: category_name)

  # cria uma subcategoria e a insere no banco, caso ela nao exista
  subcategory = Subcategory.find_or_create_by_subcategory_name(subcategory_name: subcategory_xls, category: category)

  # cria um item
  item = Item.create(item_name: item_xls, explanation: explanation_xls, information: information_xls, description: description_xls, subcategory: subcategory)

  # cria um uom
  uom = Uom.find_or_create_by_uom_name(uom_name: uom_xls, item: item)

  # cria um mtml
  mtml = Mtml.find_or_create_by_mtml_name(mtml_name: mtml_xls, item: item)

end
4

1 回答 1

0

我认为您仍然需要告诉它文件相对于您的应用程序根目录的位置。

co = Roo::Excel.new(Rails.root.join('db', 'excel.xls'))

于 2013-05-01T15:17:54.407 回答