Skip validation for some members in Devise model during password reset

前端 未结 4 1205
Happy的楠姐
Happy的楠姐 2021-01-18 12:09

My User (Devise) model also has name, city, nation, phone members.

In the create registration page - I validates_presence_of city, nation, phone, name, email,

4条回答
  •  梦谈多话
    2021-01-18 12:45

    I came across this question looking for an answer to a similar question, so hopefully someone else finds this useful. In my case, I was dealing with legacy data that had missing information for fields that were previously not required but were later made required. Here's what I did, essentially, to finish the above code:

    
    validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password
    
    def not_recovering_password
      password_confirmation.nil?
    end
    

    Basically, it uses the absence/presence of the password_confirmation field to know if a user is trying to change/reset their password. If it's not filled, they are not changing it (and, thus, run your validations). If it is filled, then they are changing/resetting, and, thus, you want to skip your validations.

提交回复
热议问题