[英]Importing excel files into rails using RubyXL
I'm trying to build a simple excel importer using RubyXL in rails to display barcode numbers.我正在尝试使用 Rails 中的 RubyXL 构建一个简单的 excel 导入器来显示条形码编号。 What i want to do is import am excel file and display the barcode results on an index page.我想要做的是导入 excel 文件并在索引页面上显示条形码结果。 I'm running into a couple errors and I'm not sure what exactly I'm missing.我遇到了几个错误,我不确定我到底错过了什么。 Here's what I have:这是我所拥有的:
Controller: Controller:
class BarcodesController < ApplicationController
def index
@barcodes = Barcode.all
end
def show
@barcode = Barcode.find(params[:id])
end
def import
Barcode.import(params[:file])
redirect_to @barcode, notice: "Barcode imported"
end
end
Model: Model:
class Barcode < ActiveRecord::Base
def self.import(file)
workbook = RubyXL::Parser.parse(params[:file].path)
worksheets = workbook.worksheets
puts "Found #{worksheets.count} worksheets"
worksheets.each do |worksheet|
puts "Reading: #{worksheet.sheet_name}"
num_rows = 0
worksheet.each do |row|
row_cells = row.cells.map{ |cell| cell.value }
num_rows += 1
end
puts "Read #{num_rows} rows"
end
end
end
View:看法:
<h2>Import Barcodes</h2>
<%= form_tag import_barcodes_path do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
Routes:路线:
Rails.application.routes.draw do
resources :users
resources :barcodes do
collection { post :import }
end
root to: "pages#root"
end
Here's the error message:这是错误消息:
NameError in BarcodesController#import
undefined local variable or method `params' for Barcode(Table doesn't exist):Class
Extracted source (around line #4):
2
3
4
5
6
7
def self.import(file)
workbook = RubyXL::Parser.parse(params[:file].path)
worksheets = workbook.worksheets
puts "Found #{worksheets.count} worksheets"
Thank you for any feedback!感谢您的任何反馈!
undefined local variable or method `params'未定义的局部变量或方法“参数”
This is because it is looking for params
local variable but it does not exist within Barcode.import
method.这是因为它正在寻找params
局部变量,但它在Barcode.import
方法中不存在。
It's super simple.超级简单。 Pass the params
from your controller to the import
method of the Barcode
model.将params
从您的 controller 传递到Barcode
model 的import
方法。
Change the method from def self.import(file)
to def self.import(params)
将方法从def self.import(file)
更改为def self.import(params)
In controller, change Barcode.import(params[:file])
to Barcode.import(params)
在 controller 中,将Barcode.import(params[:file])
更改为Barcode.import(params)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.