我將 a 中的電子郵件地址標準化before_validation,例如:
class User
before_validation do
self.email = normalized_email
end
def normalized_email
User.normalize_email(email)
end
end
但是User.find_by(email: User.normalize_email(params[:email])),例如,我必須在任何地方都這樣做,今天在嘗試查找忘記規范電子郵件地址的用戶時它咬了我,所以我希望它自動完成。
理想情況下,我不會覆寫find_by,它適用于所有方法,where例如。
我該怎么做?
uj5u.com熱心網友回復:
我只想為這個用例定義一個特殊的方法:
class User
def self.by_email(email)
find_by(email: User.normalize_email(email))
end
before_validation do
self.email = normalized_email
end
def normalized_email
User.normalize_email(email)
end
end
然后可以像這樣使用:
User.by_email(params[:email])
請注意,我明確不建議scope為此使用 a ,因為按照約定范圍應該是可鏈接的,因此ActiveRecord::Relations當您只想回傳單個記錄時,應該回傳不起作用的內容。
uj5u.com熱心網友回復:
您可以find_by在 User中覆寫以確保這種情況始終如一地發生。
class << self
def find_by(*args)
# find_by can be called without a Hash, make sure.
attrs = args.first
super unless attrs.is_a?(Hash)
# Cover both calling styles, find_by(email: ...) and find_by("email": ...)
[:email, "email"].each do |key|
# Be careful to not add email: nil to the query.
attrs[key] = normalized_email(attrs[key]) if attrs.key?(key)
end
super
end
end
這還包括find_by!,find_or_*和create_or_find_by*方法。它不涵蓋where也不原始 SQL。
您可以覆寫where,但是發生了一些奇怪的快取,這使得這很麻煩。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362797.html
下一篇:Rspec模擬和存根與期望混淆
