views:

251

answers:

2

In an ActiveRecord model, is it considered best practice/necessary to use validates_presence_of when also using validates_length_of?

For example:

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

To me, it seems redundant. Having a length between 5 and 30 means that the attribute is also present, yet I see this used everywhere. It also means users get two error messages regarding the same missing attribute, when really only one is needed.

Am I missing something, or are people being overly-zealous when validating data?

+2  A: 

People are being overly-zealous. You can use both, but the user would have a poor experience unless you pass :allow_nil to validates_length_of.

gWiz
Right, that's what I thought. :allow_nil is only useful if the company name has to be between 5 and 30 characters, or can be missing. If you want the company name to be between 5 and 30 characters long you *wouldn't* want :allow_nil.
mlambie
+4  A: 

validates_presence_of is entirely redundant when used with validates_length_of, except in cases where you supply :allow_nil => true or :allow_blank => true to validates_length_of.

Default values for the allow_nil and allow_blank options in any validation is false. validates_presence_of only fails if the attribute is neither nil, or blank. Therefore validates_presence_of is made redundant by most of the supplied validations when neither allow_nil or allow_blank is supplied as options to the validation.

EmFi