Is validates_presence_of required when using validates_length_of?

Is ActiveRecord considered best practice in the model / should validates_presence_of be used when validates_presence_of is also used?

For instance:

 class Company < ActiveRecord::Base validates_presence_of :name validates_length_of :name, :in => 5..30 end 

To me this seems redundant. A length of 5 to 30 means the attribute is also present, but I see that it is used everywhere. It also means that users receive two error messages regarding the same missing attribute when only one is really needed.

Am I missing something, or are people overly diligent when checking data?

+4
source share
2 answers

validates_presence_of is completely redundant when used with validates_length_of, unless you supply :allow_nil => true or :allow_blank => true for validates_length_of.

The default values ​​for the allow_nil and allow_blank parameters are false for any check. validates_presence_of only fails if the attribute is neither none nor empty. Therefore, validates_presence_of becomes redundant for most validations provided, when neither allow_nil nor allow_blank are provided as verification parameters.

+7
source

People are overly zealous. You can use both options, but the user will have bad experience if you fail :allow_nil to validates_length_of .

+3
source

All Articles