Rails验证重置密码时触发

时间:2015-06-28 20:50:55

标签: ruby-on-rails ruby validation devise

这是我的模特

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_many :events
has_many :appointments

validates :name, presence: true
validates :name, format: {with: /\A[[:alnum:]]+\z/, message: 'solo se permiten letras y/o numeros' }, if: 'name.present?'
validates :lastname, format: {with: /\A[[:alnum:]]+\z/, message: 'solo se permiten letras y/o numeros' }, if: 'lastname.present?'
validates :lastname, :presence => true

validates :document, :presence => true
validates_numericality_of :document, :on => :create, :message => "no es un numero", if: 'document.present?'

validates :cellphone, :presence => true
validates :cellphone, numericality:{ only_integer: true, message:"no es un numero"}, if: 'cellphone.present?', :on => :create
validates :cellphone, numericality:{ only_integer: true, message:"no es un numero"}, if: 'cellphone.present?', :on => :update
validates :cellphone, format: { with: /\d{11}/, message: "mal formato, deben ser 11 digitos, incluyendo codigo de area" }, if: "cellphone.present?", :on => :create
validates :cellphone, format: { with: /\d{11}/, message: "mal formato, deben ser 11 digitos, incluyendo codigo de area" }, if: "cellphone.present?", :on => :update

validates :phone, :presence => true
validates :phone, numericality:{ only_integer: true, message:"no es un numero"}, if: "phone.present?", :on => :create
validates :phone, format: { with: /\d{11}/, message: "mal formato, deben ser 11 digitos, incluyendo codigo de area" }, if: "phone.present?", :on => :create

validates_format_of :email,:with => Devise::email_regexp, :allow_blank => true

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

     def medic_with_spec
        "#{especialidad}, #{name} #{lastname}"          
     end

     def evento_sin 
        events.where(available: "1")
     end

你可以看到验证:手机有:on =&gt;创建和:on =&gt;更新,所以我的问题是,当我从电子邮件链接重置密码并按更新时使用新密码显示手机验证错误,因为它有:on =&gt;更新。我怎么能让这个消失?

我尝试过:&#39; cellphone.nil?&#39;,它运行正常,因为手机空白是显而易见的(重设密码只需要密码和密码确认)但是当我去编辑帐户信息时它不会验证零价值。

我正在使用设计。

我读了这个链接Validation errors are triggered when I'm trying to reset password,这是完全相同的问题,但我不知道如何实现他们所说的。

我是on ruby​​ on rails,如果some1可以帮助我,我不知道如何实现预先红宝石。

1 个答案:

答案 0 :(得分:0)

如果 password_confirmation 字段不为nil(表示密码已更改),则应禁用验证。这是一个链接主题Skip validation for some members in Devise model during password reset

所以,在你的情况下,这将是:

validates :cellphone, numericality:{ only_integer: true, message:"no es un numero"}, :if => :not_recovering_password, :on => :update

def not_recovering_password
  password_confirmation.nil?
end