Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation best practice

I have this validation for my user:

  validates :password,
  presence: true,
  confirmation: true,
  length: { minimum: 6 },
  :on => :create

This is obvious. When I'm creating (registering) a new user, I want to fill up their password hence that's why presence: true.

Case 1) When the user wants to update his account (lets say change his username), the form has only the email and username fields. That's ok and the validation is ok.

Case 2) He forgot his password and I send him his "forgotten password link" and he is on the page where he is creating his new password. The form has these two fields: password and password confirmation. However, he leaves both of these fields empty and submits the form. The validation passes because it's only :on => create! because of case 1)

I can not add :on => update because the case 1) wouldn't pass, because there is no password field.

What should I do in this situation? What is the best practice or what is the real word solution to this "problem"?

like image 819
Jakub Kohout Avatar asked Oct 31 '22 22:10

Jakub Kohout


1 Answers

What I have done for this situation is instead of using on: :create, I use a virtual attribute that I set only when setting/changing the password. Something like this:

validates :password, if: :changing_password?
attr_accessor :password_scenario

def changing_password?
  self.password_scenario.present?
end

Then in your controller, you would simply set password_scenario to true whenever you are requiring password to be present.

like image 140
dgross Avatar answered Nov 15 '22 05:11

dgross