是否可以对所有查找器方法对属性进行规范化?



假设我有一个 Rails 5 模型,其属性需要规范化,例如 url 或电子邮件。

class Person < ApplicationRecord
# Using the attribute_normalizer gem
normalize_attributes :email, with :email
...
end

我希望当在该模型上使用查找器方法时,该搜索属性也会规范化。例如。。。

# This would match 'foo@example.com'
person = Person.find_by( email: 'FOO@EXAMPLE.COM' )
# This would also match 'foo@example.com'
person = Person.find_by( email: 'foo+extra@example.com' )

我尝试提供自己的Person.find_by认为其他查找器方法最终会调用它。

def self.find_by(*args)
attrs = args.first
normalize_email_attribute(attrs) if attrs.kind_of?(Hash) 
super
end

这适用于Person.find_by,但是尽管Rails内部使用find_by来寻找其他查找方法,如find_or_create_by,但他们不调用Person.find_by。我必须覆盖单个查找器方法。

def self.find_or_create_by(attrs, &block)
normalize_email_attribute(attrs)
super
end
def self.find_or_create_by!(attrs, &block)
normalize_email_attribute(attrs)
super
end

有没有办法规范化所有查找器方法的特定模型上的搜索属性?或者也许更好地完成同样的事情?

Rails 7.1 新增ActiveRecord::Base::normalizes

class User < ApplicationRecord
normalizes :email, with: ->(email) { email.strip.downcase }
end

它适用于持久性和查找器方法

User.create(email: " ASDF@ExAmPLE.com n")
# => #<User email: "asdf@example.com">
User.find_by(email: "nasdf@examplE.CoM t")
# => #<User email: "asdf@example.com">

最新更新