开发者

Rails 3: validates :presence => true vs validates_presence_of

开发者 https://www.devze.com 2023-02-19 15:21 出处:网络
What is the difference between validates :presence and validates_presence_of? Looking through ActiveModel it looks like they setup the validation the same way. However, given the following model defin

What is the difference between validates :presence and validates_presence_of? Looking through ActiveModel it looks like they setup the validation the same way. However, given the following model definition:

class Account < ActiveRecord::Base
  has_one :owner_permission, :class_name => 'AccountPermission', :conditions => { :owner => t开发者_JAVA百科rue, :admin => true }
  has_one :owner, :class_name => 'User', :through => :owner_permission, :source => :user

  validate :owner, :presence => true
  validates_associated :owner
end

Calling save on an instance of Account does not validate the presence of owner. Though, if I use validates_presence_of it will.


All those validates_whatever_of :attr macros do is call validates :attr, :whatever => true.

The problem is you are using validate and not validates.


In Rails 3.x and 4.x - it is now encouraged to use the following syntax:

validates :email, presence: true
validates :password, presence: true

Instead of the 2.x way:

validates_presence_of :email
validates_presence_of :password


In fact validates and validates_presence_of is not entirely equal !

validates_presence_of is allowing you to also lazily check by example of the value in the field is included in another table.

Like that:

validates_presence_of :pay_type, :inclusion => PaymentType.names

Which is something you can't do as easily with something like that

validates :pay_type, presence, :inclusion => PaymentType.names

Cause the inclusion is only evaluated the first time (not in a lazy way)


I would have thought that it is appropriate to use validates :foo presence: true when you want to include other validations of :foo such as length or uniqueness. But if you know the only validation you'll need for an attribute is presence, then validates_presence_of appears to be more efficient.

So:

validates :foo, length: {maximum: 50}, uniqueness: true, 
                format: {with: /bar/}, 
                presence: true # lots of validations needed

But:

validates_presence_of :foo # only presence validation needed
0

精彩评论

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