Rails 3 validates an action-based rule

This seems like a simple question, but it seems that I can not find the answer to the question about writing custom validators. I have this validator

validates :password, :presence => true, :confirmation => true, :length => { :minimum => 5} 

there are more rules, such as some regex for complexity, but that gives the gist.

The problem is that I want the application to be created only for creation, everything else needs to be created and updated. Since the user may not change the password when updating his information.

I tried to break the rules

 validates :password, :presence => true, :on => :create validates :password, # The rest of the rules 

This led to ignoring all the rules for updating. Is there an easy way to apply only one rule to create, and the rest to everything?

+6
source share
2 answers

You can try to save it in one line, but applying :on => :create only to the tag :presence :

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

However, I'm not sure that it makes sense to always require a minimum length, but it does not always require availability - if you update an existing record with an empty password, this will still lead to a validation failure, since the length is 0.

+6
source

My guess is that the problem is that the check: the password call is not additive. You can switch the presence check to:

 validates_presence_of :password, :on=>:create 

And then save your other checks with validation. It works?

0
source

Source: https://habr.com/ru/post/887370/


All Articles