这是我的用户类:
class User < ActiveRecord::Base
has_secure_password
before_save :valid_email?
validates :username, presence: true,
uniqueness: true
validates :first_name, presence: true
enum role: [ :flyer, :admin ]
def valid_email?
email_checker
end
private
def email_checker
self.email.match(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/)
end
end
这是我的测试:
test "if a user has an invalid email, cannot be saved" do
user = build(:user)
user1 = build(:user, email: "here@here@here")
user2 = build(:user, email: "here.here@here")
assert user.save
refute user1.save
refute user2.save
end
如果电子邮件在@ here @ here或here.here@here,则email_checker方法返回nil。那是怎么回事?
答案 0 :(得分:3)
因为你只需要调用self.email.match
方法。如果要验证字段,则应使用或创建验证器。
在您的情况下,您可以创建own custom validator或使用来自宝石的电子邮件验证器(即email_validator)。