0

I've looked around and can't find any info on this.

I've already built my User Model and ran my migrations. Now, I've got to populate the existing user table in my database with data from a csv file that only has email and name. The problem is none of the users have passwords yet. So I need to create a temporary password for all of the users. I'm using devise for authentication, so the password needs to work for Devise's encryption.

How do I do this?

DaveG
  • 1,203
  • 1
  • 25
  • 45

2 Answers2

2

You can parse a CSV file in Ruby, iterate through all the records and create the users with a temporary password.

You can read a csv file with ruby's CSV class:

CSV.open('my_file.csv','r') do |row|
  #do something with the row, e.g. row['first_name']
end

Once you have extracted the fields from the CSV you can use something like this to generate a temporary password:

o =  [('A'..'Z'), (1 .. 9)].map{|i| i.to_a}.flatten;  
temp_password = (0..8).map{ o[rand(o.length)]  }.join;

This will generate a password containing capital letters and numbers 1-9 with a length of 8 characters (i use this to generate invite codes in my current project)

So to put it all together you can do something like this:

CSV.open('my_file.csv','r') do |row|
  email = row['email']
  name = row['name']
  #This would be better in a seperate method
  o =  [('A'..'Z'), (1 .. 9)].map{|i| i.to_a}.flatten;  
  temp_password = (0..8).map{ o[rand(o.length)]  }.join;
  User.create(:email => email, :password => temp_password, :password_confirmation => temp_password)
end

Hope that points you in the right direction!

GracelessROB
  • 1,048
  • 8
  • 11
0

You can create a new Devise user simply by creating a new user model (see https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface)

user = User.new(:email => 'test@example.com', :password => 'password', :password_confirmation => 'password')
user.save

refer to : https://stackoverflow.com/a/4660842/445908

Community
  • 1
  • 1
Siwei
  • 19,858
  • 7
  • 75
  • 95
  • Thanks for the response. I understand how to create a new user. I already have the model built. The problem is I have a list of emails and names in a database that I need to insert into the existing user database. The users do not currently have passwords, so I need to give them temporary ones. – DaveG Oct 20 '12 at 06:01
  • If you need to update the "users" table without touching the "passwords", then I suggest you just generate "raw SQL"s and execute them. – Siwei Oct 20 '12 at 06:02