Search code examples
ruby-on-railscsvdevisepg

Creating devise users from a CSV file - Rails - PG


I have been given a CSV file that contains emails and passwords.

My task is to go through this CSV file and create users using the devise gem.

You will probably wonder why I hace been given peoples emails and passwords (I am as well), but I've been told not to worry about it.

My csv file looks like this:

Email,Password,Password_confirmation,,
[email protected] ,password1,password1,,
[email protected] ,password2,password2,,
[email protected] ,password3,password3,, 

I wrote the following code in my seeds.rb file:

require 'csv'
CSV.foreach("db/fixtures/users.csv", :col_sep => ",", :headers => true) do |row|
User.create(email: row['email'], password: row['password'], password_confirmation: row['password_confirmation'])
end

I run rails db:seed to create the users, but nothing happens, no error messaged either.

Any support would be welcomed.


Solution

  • First of all, it's a really bad idea to put that file with actual passwords under version control and to import it in seeds.rb. Would be much better to add a rake task for that purpose accepting csv file path as an argument and perform it once in a suitable environment.

    About the code, the headers in CSV import are case sensitive, so it would work if you get the row value via row['Email'], row['Password'] etc. Also, make sure that filling in those fields are enough to save the user, there may be some other required fields in your particular model.