0
我跟隨Ryan Bates的railcast教程,通過導軌應用程序導入excel文件。 我的Ruby版本是2.2.4,rails版本是4.2.6 我已經安裝了'roo'gem。在rails應用程序中導入excel文件
我的應用程序\型號\ user.rb文件是:
class User < ActiveRecord::Base
require 'csv'
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]
user=find_by_id(row["id"])||new
user.attributes=row.to_hash.slice(*accessible_attributes)
user.save
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
#when ".csv" then Roo::Csv.new (file.path nil, :ignore)
when ".xls" then Roo::Excel.new (file.path)
#when ".xlsx" then Excelx.new (file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
end
我的應用程序\控制器\ users_controller.rb文件是:
class UsersController < ApplicationController
def index
@users=User.all
end
def import
User.import(params[:file])
redirect_to root_url, notice: "Activity data imported!"
end
end
現在我的應用程序的主頁是否正常工作。但是,從當我點擊文件選擇selectiong後的文件「excel導入」按鈕(我所做的這一切在index.html.erb文件),,然後它顯示了以下錯誤:
RuntimeError in UsersController#import
could not locate a workbook, possibly an empty file passed
還不能解決這個問題。 open_spreadsheet方法已經在那裏定義了,那麼錯誤的原因是什麼?
仍然是一樣的錯誤,,,沒有發生任何事情 – Abhradip
你在第一個循環後缺少和「結束」 – ryudice
現在它在UsersController中帶有SyntaxError#import – Abhradip