我正在试图弄清楚如何创建一个共享的自定义验证,我可以在我放在lib / validations.rb文件夹中的模型中使用它。
module Validations
extend ActiveSupport::Concern
# included do
def email_format_validation
if self.email.present?
if !validates_format_of :email, with: email_regex
self.errors.add(:email, "doesn't exist")
end
end
end
def email_regex
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
end
所以在我的模型中,这允许我这样做:
validate :email_format_validation
在其他模型中,我试图调用email_regex
:
validate :user_email, with: email_regex
这会产生以下错误:
undefined local variable or method `email_regex' for #<Class....>
我试过在我的模型中使用include Validations
,extend Validations
,require 'validations'
等,但没有运气。我也尝试将模块方法放在class << self
中,使用included do
块,将方法设置为self.email_regex
并调用Validations.email_regex
但似乎没有任何效果。
我尝试了以下内容,它对我有用:
在模型/关注点中创建了validations.rb
module Validations
extend ActiveSupport::Concern
def email_format_validation
if self.email.present?
if !validates_format_of :email, with: email_regex
self.errors.add(:email, "doesn't exist")
end
end
end
def email_regex
/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
end
在模型中:
include Validations
class User < ApplicationRecord
validate :email_format_validation
validates :user_email, with: :email_regex
end
user_email是字段名称
您是否尝试过使用require_relative Validations