Reputation: 2482
I want to import users with a CSV file so I put this code in lib/task/import.rake :
require 'csv'
task :import => :environment do
CSV.foreach('db/test.csv', :headers => true) do |row|
UserManager::User.create!(row.hash)
end
end
Here is my CSV test file :
surname;name;email;password;password_confirmation
test;test;[email protected];pass;pass
And when I run rake import
I get this error :
When assigning attributes, you must pass a hash as an argument.
Why did I get this error ?
Upvotes: 0
Views: 104
Reputation: 9165
Those variables aren't comma separated, they're semicolon separated. So:
CSV.foreach('db/test.csv', headers: true, col_sep: ";")
Upvotes: 2
Reputation: 8638
To sum up the comment of Pavan and the solution of gunn, your code should be:
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
Upvotes: 2
Reputation: 2472
Try this ............
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
Hope this will work for you.
Upvotes: 0
Reputation: 281
Use this
require 'csv'
CSV.foreach(file.path, headers: false) do |row|
user_hash = {}
user_hash = {"surname"=> name,"last_name"=> last_name } #key value
User.create!(user_hash)
end
end
Upvotes: 0
Reputation: 5015
I think it should be
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
will return an integer
Upvotes: 0