【发布时间】:2016-01-14 08:27:18
【问题描述】:
请帮助导入 csv 文件。
我安装 gem 'roo' 和 gem 'iconv'。我为导入文件制作脚手架产品和表格:
<%= form_tag import_products_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
config/routes.rb
resources :products do
collection { post :import }
end
products_controller.rb
def import
Product.import(params[:file])
redirect_to root_url, notice: "Products imported."
end
models/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.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Csv.new(file.path, nil, :ignore)
when ".xls" then Excel.new(file.path, nil, :ignore)
when ".xlsx" then Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
我使用这个流行的教程:http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true
但通过表单加载 csv 文件后,浏览器显示如下:
NameError in ProductsController#import
uninitialized constant Csv
和控制台显示跟随错误
message:#<ActionDispatch::Http::UploadedFile:0x000000060f36a0 @tempfile=#<Tempfile:/tmp/RackMultipart20151015-18667-14nvfde.csv>, @original_filename="products (2).csv", @content_type="text/csv", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"products (2).csv\"\r\nContent-Type: text/csv\r\n">
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.0ms)
NameError (uninitialized constant Csv):
app/models/product.rb:25:in `open_spreadsheet'
app/models/product.rb:11:in `import'
app/controllers/products_controller.rb:82:in `import'
我尝试替换模型:
when ".csv" then Csv.new(file.path, nil, :ignore)
在
when '.csv' then Roo::Csv.new(file.path, nil, :ignore)
但问题没有解决。
在这个主题中,我向 Suraj 询问了有关调整的问题,但没有收到任何回复。
请帮忙导入 csv 文件
【问题讨论】:
-
你实现了 config/application.rb require 'csv' require 'iconv' 部分吗?
-
Roo::CSV.new(file.path, nil, :ignore) 我得到的这可能会解决你的错误
标签: ruby-on-rails ruby csv import