【问题标题】:Query with OR condition through an association通过关联查询 OR 条件
【发布时间】:2013-09-12 17:26:16
【问题描述】:

我正在尝试通过用户名或电子邮件帮助查找用户记录。唯一的问题是用户名存储在关联的UserDetail 模型中。

class User
  has_one :user_detail

  def self.find_by_username_or_email(value)

    # This is effectively pseudocode for the query I'd like to write.
    query = "lower(email) = :value OR user_detail.username = :value"
    where([query, { value: value }]).first
  end
end

如何编写与关联user_detail 记录上的电子邮件或用户名匹配的查询?

【问题讨论】:

  • 冷静下来 Yoshiji :-) 我早上回来工作时会好好看看。如果对您有帮助,您将获得奖励!

标签: mysql sql ruby-on-rails activerecord ruby-on-rails-3.2


【解决方案1】:

你快到了!

这应该适合你:

class User < ActiveRecord::Base
  has_one :user_detail

  def self.find_by_username_or_email(value)
    query = "lower(users.email) = :value OR user_details.username = :value"
    includes(:user_detail).where(query, value: value).first
  end
end

【讨论】:

  • 此查询运行时间过长。大约有 27k 行的 users 表大约需要几分钟。有什么建议可以让它更快吗?
  • 解决了速度问题。这要快得多:joins(:user_detail).where(query, value: value).first,因为它使用INNER JOIN 而不是LEFT OUTER JOIN
【解决方案2】:

看来你需要写

self.includes(:user_detail).where(" user.email = ? OR user_detail.user_name =?", param[1], param[2])

【讨论】:

  • 你需要使用includes(:user_detail)(单数),因为关系被声明为has_one :user_detail(单数)。
猜你喜欢
  • 1970-01-01
  • 2011-08-14
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多