FasterCSV 用于在 Rails 中导入用户
你好, 我正在尝试使用 FasterCSV 从 CSV 文件导入用户
在我的用户控制器中,
<form action='/users/bulk_create' method='post'>
<%= file_field_tag "csv_file" %><br/>
<%= submit_tag("Import") %>
</form>
我有一种方法,例如
def bulk_create
login, password, name, email = 0, 1, 2, 3
require 'fastercsv'
parsed_rows=FasterCSV.parse(params[:csv_file])
parsed_rows.each do |row|
puts "#{row[name]}"
end
end
当我执行上述操作并在日志中检查它时,我收到错误,因为
NoMethodError (undefined method `pos' for nil:NilClass):
app/controllers/users_controller.rb:688:in `bulk_create'
FasterCsv 根本不读取文件。 如何让它能够阅读 我使用 sudo gem install fastcsv 安装了 gem
HI,
I am trying to use FasterCSV to import users from a CSV file
I have
<form action='/users/bulk_create' method='post'>
<%= file_field_tag "csv_file" %><br/>
<%= submit_tag("Import") %>
</form>
In my users controller i have a method like
def bulk_create
login, password, name, email = 0, 1, 2, 3
require 'fastercsv'
parsed_rows=FasterCSV.parse(params[:csv_file])
parsed_rows.each do |row|
puts "#{row[name]}"
end
end
When i do the above and inspect it in the log i am getting the error as
NoMethodError (undefined method `pos' for nil:NilClass):
app/controllers/users_controller.rb:688:in `bulk_create'
FasterCsv is not reading the file at all.
How to make it to read
I installed the gem using sudo gem install fastercsv
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您要上传文件,因此必须将表单的
enctype
属性指定为multipart/form-data
其次,您不能传递
params[:csv_file] 直接保存到 FasterCSV,您需要对数据进行完整性检查,然后将其保存为 csv 文件。
看看这里,http://www.tutorialspoint.com/ ruby-on-rails/rails-file-uploading.htm 它提供了文件上传的基础知识。我强烈建议您查看文件上传插件,例如“Paperclip”等。
然后保存文件后,“FasterCSV”的文档建议
Since you are uploading a file, you must specify the
enctype
attribute for your form asmultipart/form-data
Secondly you cannot pass
params[:csv_file]
directly to FasterCSV, you need to sanity check the data and then save it as a csv file.Have a look here, http://www.tutorialspoint.com/ruby-on-rails/rails-file-uploading.htm which gives the basics of file uploading. I would strongly suggest looking at file upload plugin like "Paperclip" or the likes.
Then after you have saved the file, and the docs for "FasterCSV" suggest
它也有效:
It also works: