设计`find_first_by_auth_conditions`解释

时间:2014-04-14 14:48:39

标签: ruby-on-rails ruby activerecord devise

我很难理解Devise中的代码,即使我已经阅读了文档并做了一些研究。

def self.find_first_by_auth_conditions(warden_conditions)
  conditions = warden_conditions.dup
  signin = conditions.delete(:signin)
  where(conditions).where(["lower(username) = :value OR lower(email) =
    :value", {:value => signin.downcase }]).first
end

请解释上述方法的这一部分的组成部分:

where(conditions).where(["lower(username) = :value OR lower(email) =
  :value", {:value => signin.downcase }]).first

1 个答案:

答案 0 :(得分:2)

# arg is Hash, so assign to variable and downcase
x = warden_conditions[:signin].downcase

# create duplicate to preserve orig
c = warden_conditions.dup

# delete `:signin`
c.delete(:signin)

# if email, only search for email
if x =~ /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
  y = self.where(c).where(:email => x) # self is implied, but optional--so we use it here for clarity 

# if not email, only search for name
else
  y = self.where(c).where(:username => x)
end

# y is array, so should be only one AR obj or empty array considering they are unique
# `Array#first` will return `nil` or AR obj
return y.first

正则表达式: validate email with regex jquery

以上代码将列emailusername的所有先前记录视为小写,如下所示:

before_save :downcase_fields

def downcase_fields
  self.email.downcase
  self.username.downcase
end