我环顾四周,找不到任何关于此的信息。
我已经构建了我的用户模型并运行了我的迁移。 现在,我必须使用来自仅具有电子邮件和名称的csv文件中的数据来填充数据库中的现有用户表。问题是用户还没有密码。所以我需要为所有用户创建一个临时密码。我正在使用devise进行身份验证,因此密码需要适用于Devise的加密。
我该怎么做?
答案 0 :(得分:2)
您可以在Ruby中解析CSV文件,遍历所有记录并使用临时密码创建用户。
您可以使用ruby的CSV类读取csv文件:
CSV.open('my_file.csv','r') do |row|
#do something with the row, e.g. row['first_name']
end
从CSV中提取字段后,您可以使用类似的方法生成临时密码:
o = [('A'..'Z'), (1 .. 9)].map{|i| i.to_a}.flatten;
temp_password = (0..8).map{ o[rand(o.length)] }.join;
这将生成一个包含大写字母和数字1-9的密码,长度为8个字符(我用它来生成当前项目中的邀请码)
所以要把它们放在一起你可以做这样的事情:
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
希望指出你正确的方向!
答案 1 :(得分:0)
您只需创建新的用户模型即可创建新的Devise用户(请参阅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