开发者

Is validates_presence_of necessary if using validates_length_of?

In an ActiveRecord model is it considered best practice/necessary to us开发者_如何转开发e 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜