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, :on => :create
In the edit registration page - I validates_presence_of city, nation, phone, name, :on => :update
Now when I set a new password on forgot_password_page, it asks for the presence of city, nation, phone, name inside Devise::PasswordsController#update
How can I handle selective validations?
I am guessing it should be something like,
validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password
def not_recovering_password
# what goes here
end
I had a similar problem because when my User is created not all its fields are required. The other fields' presence is checked on: :update
using a validation.
So this is how I solved:
validates :birthdate, presence: true, on: :update, unless: Proc.new{|u| u.encrypted_password_changed? }
The method encrypted_password_changed?
is the one used in the Devise Recoverable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With