开发者

Generate a new user programmatically (Auth Logic)

I'm quite new to Ruby on Rails so please bear with me :)

I'm processing an imported .csv file in Rails and I want to programmatically create new users (I'm using the AuthLogic Gem along with Role Requirement), So Far I'm 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 being that this doesn't add a new user, it tries to but fails (DB Begin followed by Rollback), I assume because I'm not filling in all the fields, such as login, password etc.

Do I have to explicitly generate values for th开发者_开发百科ese fields?


I came across this same problem yesterday. I'm using the oauth addon though so the login/email are not required fields for me, it was failing on the persistence token not being present which I got around by adding

user.reset_persistence_token

just before calling user.save

Hope that helps a bit. Would be nice to find a cleaner way of doing it.


Ok So I've managed to answer my own question, although not in the most ideal of ways:

 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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜