我如何参考RoR 5中的模块实例方法中的模型属性
问题描述:
我想将我的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'
任何帮助,将不胜感激!
答
这是一个很好的常用方法,但Rails提出了这种情况的担忧。 http://api.rubyonrails.org/v5.1/classes/ActiveSupport/Concern.html
在你的情况下,代码将是:
# file in models/concerns/model_utilities.rb
module ModelUtilities
extend ActiveSupport::Concern
included do
before_validation :downcase_email
end
def downcase_email
email.downcase!
end
end
# include your concern
class User < ApplicationRecord
include ModelUtilities
end
看before_validation
可以移动到担忧。
'self.email = email.downcase如果email.present? '。 另外,你最好使用'before_validation'回调,而不是'before_save'。只有在电子邮件发生变化时才会进行降级,而不是所有的时间。 'before_validation:downcase_email,如果:: email_changed?' – chumakoff
@xlembouras就是这样。错误将在“包括”,如果这是问题:) – P0lska
检查什么来自我和使用self.email.downcase而不是电子邮件.downcase –