Generating a new user programmatically (Auth Logic)
I'm quite new to Ruby on Rails, so please bear with me :)
I am processing an imported .csv file in Rails and want to programmatically create new users (I am using AuthLogic Gem along with Role Requirement). So far I am using:
Example line:
Steve.Jobs@apple.com, Steve, Jobs, 555-APPLE
Code:
def new_user(line)
params = Hash.new
params[:user] = Hash.new
params[:user]["email"] = line[0]
params[:user]["first_name"] = line[1]
params[:user]["last_name"] = line[3]
params[:user]["phone"] = line[4]
user = User.new(params[:user])
user.save
end
The problem is this doesn't add a new user, it tries but fails (DB Begin and then Rollback), I guess because I don't fill in all the fields like login, password, etc.
Do I have to explicitly generate values ββfor these fields?
source to share
So, I was able to answer my own question, although not in the most ideal way:
def new_user(line)
params = Hash.new
params[:user] = Hash.new
params[:user]["email"] = line[0]
params[:user]["first_name"] = line[1]
params[:user]["last_name"] = line[2]
params[:user]["phone"] = line[3]
#generate random password of length 6
password = ActiveSupport::SecureRandom.base64(6)
#generate username by adding first and last name + 3 random characters
username = (line[1] + line[2])
username = username + ActiveSupport::SecureRandom.base64(3)
params[:user]["login"] = username
params[:user]["password"] = password
params[:user]["password_confirmation"] = password
#check to see if user already exists
@existing_user = User.find_by_email(line[0])
if(@existing_user)
#user exists
#do nothing
else
#user is brand new
@new_user = User.new(params[:user])
@new_user.reset_persistence_token
if(@new_user.save)
@new_user = User.find_by_email(line[0])
#user saved successfully
else
#a problem occurred
flash[:errors] = @new_user.errors
end
end
end
source to share
I ran into this problem yesterday. I am using the oauth addon, although so the login / email are not required fields for me, it was unfortunate when the persistence token was not present which I got by adding
user.reset_persistence_token
before calling user.save
Hope it helps. It would be nice to find a cleaner way to do this.
source to share