ruby on rails - Use multiple database fields to identify users for login -


i'm developing ror application requirement users can log in of 4 possible identifiers: email, home phone #, primary phone #, or work phone #. current solution use regex see if it's correctly formed email address, , if isn't, search users table each of 3 types of phone fields in succession.

# did user try log in email? if is_email params[:session][:login_param]     user = user.find_by(email: params[:session][:login_param].downcase) else    # if login parameter isn't email...     # try finding user home number     user = user.find_by(phone_home: params[:session][:login_param])     if user.nil?         # try finding user cell number         user = user.find_by(phone_cell: params[:session][:login_param])     end     if user.nil?         # try finding user work number         user = user.find_by(phone_work: params[:session][:login_param])     end end # verify password user.authenticate() 

my problem has potential search entire users table 3 times if user record near end of table tries logging in work number; don't know if make logins slow in production.

is there cleaner/faster way this?

this should work long validate uniqueness of phone numbers on creation.

class user    def self.find_by_login(login)       where("email = ? or phone_home = ? or phone_cell = ? or phone_work = ?",*([login] * 4)).limit(1)   end end @user = user.find_by_login(params[:session][:login_params]) #this generate following query login_params = 'hello' #=> "select \"users\".* \"users\"  (email = 'hello' or phone_home = 'hello' or phone_cell = 'hello' or phone_work = 'hello')" #authenticate @user  

edit

as pointed out original version returned array using added limit(1) return instance of user. mentioned must validate uniqueness each of fields make sure pull correct record.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -