通过关联查询OR条件

时间:2013-09-12 17:26:16

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

我正在尝试通过用户名或电子邮件来查找用户记录。唯一的问题是用户名存储在关联的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记录中的电子邮件或用户名相匹配的查询?

2 个答案:

答案 0 :(得分:2)

你快到了!

这应该适合你:

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

答案 1 :(得分:1)

好像你需要写

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