gpt4 book ai didi

mysql - (Rails + Devise)将数据插入数据库并填充密码

转载 作者:行者123 更新时间:2023-11-29 08:44:07 27 4
gpt4 key购买 nike

我环顾四周,找不到任何相关信息。

我已经构建了我的用户模型并运行了我的迁移。现在,我必须使用仅包含电子邮件和姓名的 csv 文件中的数据填充数据库中的现有用户表。问题是所有用户都没有密码。所以我需要为所有用户创建一个临时密码。我正在使用devise用于身份验证,因此密码需要用于 Devise 的加密。

我该怎么做?

最佳答案

您可以在 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

希望能为您指明正确的方向!

关于mysql - (Rails + Devise)将数据插入数据库并填充密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12985659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com