【问题标题】:Passing in multiple hash slices to an Activerecord query将多个哈希切片传递给 Activerecord 查询
【发布时间】:2014-02-24 11:34:28
【问题描述】:

我有以下代码(它没有按我的意愿工作)

def self.from_omniauth(auth)
where(auth.slice(:provider, :uid) || auth.info.slice(:email)).first_or_initialize.tap do |user|
  user.provider = auth.provider
  user.uid = auth.uid
  user.name = auth.info.name
  user.email = auth.info.email
  user.oauth_token = auth.credentials.token
  user.oauth_expires_at = Time.at(auth.credentials.expires_at)
  if user.password = ""
    temp_pass = SecureRandom.urlsafe_base64
    user.password = temp_pass
    user.password_confirmation = temp_pass
  end
  user.save!
end

结束

我要创建的是一个 activerecord where 子句,例如:

User.where("provider = ? AND uid = ? OR email = ?", "facebook",    "1569037127","turt13@example.com")

执行此代码时生成的 SQL 不包括 OR 语句或对电子邮件字段的任何引用。

用户负载 (0.2ms) SELECT "users".* FROM "users" WHERE "users"."provider" = 'facebook' AND "users"."uid" = '100007760885613' ORDER BY "users" id" ASC 限制 1

在这方面的任何帮助都会很棒......

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    这是因为你告诉它做这个或那个,而不是用and或in进行查询。

    你为什么不能这样做:

    where("provider = ? AND uid = ? OR email = ?", auth["provider"], auth["uid"], auth["info"]["email"])
    

    和你下面的差不多吗?

    【讨论】:

    • 好的,我明白你在说什么。但是,当我按照建议执行时,如果在日志中创建如下 SQL 语句:SELECT "users".* FROM "users" WHERE (provider = '#<:authhash provider="facebook">' AND uid = ' #<:authhash uid="100007760885613">' OR email = '#<:authhash::infohash email="richard_dfrsvld_goldstein@tfbnw.net">') ORDER BY "users"."id" ASC LIMIT 1
    • 谢谢。我传递的是哈希而不是值。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2019-03-16
    • 2013-08-10
    相关资源
    最近更新 更多