【问题标题】:Devise `find_first_by_auth_conditions` explanation [duplicate]设计`find_first_by_auth_conditions`解释[重复]
【发布时间】:2014-04-14 14:48:38
【问题描述】:

我很难理解来自 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

【问题讨论】:

  • 根据warden 条件运行的查询的第一个结果加上用户名或电子邮件等于登录值。有什么问题?
  • @DaveNewton:谢谢,你能把它分解成更简单的形式吗?我无法理解它的整体。
  • warden_conditions.dup - 复制守望者条件。然后conditions.delete(:signin) 删除登录值。然后找到具有这些条件的第一条记录,并且用户名或电子邮件是 Dave 所说的登录值
  • 你可能对conditions.delete(:signin)返回删除的值感到困惑?
  • 任何人都可以编写相同的查询。 where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => signin.downcase }]).first

标签: ruby-on-rails ruby activerecord devise


【解决方案1】:
# 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

【讨论】:

  • 感谢您提供整个代码,但您的代码又与此有什么关系.. where(conditions).where(["lower(username) = :value OR lower(email) = :value ", { :value => signin.downcase }]).first
  • 你能写出等价的查询吗?
  • @theJava 基本上它不等价,但足够接近用于说明目的。希望能帮助到你。 lower(username)signin.downcase 查询列,就好像它都是小写的一样,所以设计不需要知道是否有任何记录是用大写或小写字符存储的。
  • where(["lower(username) = :value OR lower(email) = :value", { :value => signin.downcase }]).first 这部分代码是否执行检查哪里(条件)
  • @theJava 正则表达式是用两个查询来解释“漫长的道路”,设计查询使用OR 变成一个查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多