我想用CSV文件导入用户,所以我把这段代码放在lib / task / import.rake中:
TypeError: Cannot read property 'match' of null
这是我的CSV测试文件:
require 'csv'
task :import => :environment do
CSV.foreach('db/test.csv', :headers => true) do |row|
UserManager::User.create!(row.hash)
end
end
当我运行surname;name;email;password;password_confirmation
test;test;test@exemple.fr;pass;pass
时,我收到此错误:
rake import
为什么我收到此错误?
答案 0 :(得分:2)
这些变量不以逗号分隔,它们以分号分隔。所以:
CSV.foreach('db/test.csv', headers: true, col_sep: ";")
答案 1 :(得分:2)
总结Pavan的评论和gunn的解决方案,你的代码应该是:
require 'csv'
task :import => :environment do
CSV.foreach('db/test.csv', :headers => true, col_sep: ';') do |row|
UserManager::User.create!(row.to_hash)
end
end
答案 2 :(得分:0)
我认为应该是
require 'csv'
task :import => :environment do
CSV.foreach('db/test.csv', :headers => true) do |row|
UserManager::User.create!(row.to_hash)
end
end
row.hash
将返回一个整数
答案 3 :(得分:0)
使用此
*.blade.php
答案 4 :(得分:0)
试试这个............
require 'csv'
#file with full path
file = "#{Rails.root}/public/file_name.csv"
#Reading file
user_file = CSV.read(file, :headers => true)
#Creating User
user = UserManager::User.where(:email => user_file['email']).first_or_create
if user.present?
user.name = user_file['email']
#Same other data ......
user.save!
end
希望这对你有用。