我想将我的downcase_email方法从我的User类中移出,因为我有多个需要使其电子邮件缩减的类。我不确定这是否是正确的方法,但我创建了一个模块并将其移入其中。我如何参考RoR 5中的模块实例方法中的模型属性
class User < ApplicationRecord
include ModelUtilities
before_save :downcase_email
# downcase_email was previously here
#
# def downcase_email
# self.email = email.downcase
# end
end
文件中的lib/model_utilities.rb
module ModelUtilities
def downcase_email
self.email = email.downcase
end
end
当我运行代码,我得到以下错误:
NoMethodError (undefined method `downcase' for nil:NilClass):
lib/model_utilities.rb:6:in `downcase_email'
任何帮助,将不胜感激!
'self.email = email.downcase如果email.present? '。 另外,你最好使用'before_validation'回调,而不是'before_save'。只有在电子邮件发生变化时才会进行降级,而不是所有的时间。 'before_validation:downcase_email,如果:: email_changed?' – chumakoff
@xlembouras就是这样。错误将在“包括”,如果这是问题:) – P0lska
检查什么来自我和使用self.email.downcase而不是电子邮件.downcase –