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