因此,我试图在我的应用程序中构建一个功能,允许用户上传一个充满新产品的电子表格文件。我安装了Roo宝石。我创建了一个链接,供用户下载一个模板化的谷歌电子表格,用于将产品上传到我的应用程序。为了测试这个特性,我使用这个模板表上传到我的应用程序。
第一行标题具有在数据库中创建产品所需的属性的名称。
我能够上传的文件,但是,无论有多少产品列在文件中,它只会上传一个产品。此外,导入的产品具有与文件中的属性相关联的-零值。我可以通过Rails控制台验证这一点。
例如:姓名:零,描述:零,等等。
这是我的Product.rb文件中的对应代码:
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
def self.accessible_attributes
['name', 'description', 'category', 'barcode', 'quantity',
'capacity', 'threshold']
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end这就是我如何设置我的路由:
resources :products do
collection { post :import }
end发布于 2017-06-08 21:44:45
好的,我遇到的问题是,在导入的电子表格中,标题行大写,而不是小写。能力、阈值和数量属性也有问题,因为它们不是产品模型的一部分。
一旦我编辑了电子表格,并删除了它正确导入的这三个属性,没有任何错误。
发布于 2017-06-06 11:47:50
注意:一个电子表格有多个工作表,所以您要做的是
spreadsheet = open_spreadsheet(file) # this return a spreadsheet
sheet1 = spreadsheet.sheet(0) # this will return the first sheet
puts spreadsheet.sheets # show all sheetshttps://stackoverflow.com/questions/44371735
复制相似问题