請幫忙導入csv文件。如何通過'roo'gem導入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
型號/ 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關於調整,但沒有收到任何迴應。
請幫助impoer CSV文件
你實現 的config/application.rb中 需要 'CSV' 要求'iconv' 部分? – peter
是的。我實現的是 – stackow1
Roo :: CSV.new(file.path,nil,:ignore)我得到這個可能會解決你的錯誤 –