我目前正在开发一个系统,其中仅当用户不是学生时才需要电子邮件,而如果用户是学生则需要用户名。 这就是我在模型中所做的:
class User < ActiveRecord::Base
validates :email, presence: true, unless: :student?
validates :username, presence: true, if: :student?
end
这在用户名属性上效果很好,但对于电子邮件,我仍然收到电子邮件不能为空
错误。我猜 Devise 有自己的电子邮件验证规则。
我怎样才能做到这一点,我的意思是覆盖设计验证电子邮件的存在规则?
谢谢
最佳答案
Devise 有一个 email_required?
方法,可以用一些自定义逻辑覆盖。
class User < ActiveRecord::Base
validates :username, presence: true, if: :student?
protected
def email_required?
true unless student?
end
end
关于ruby-on-rails - Rails 4 和 Devise : Allow email blank on certain conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649311/