可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 => true, :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.
回答1:
All those validates_whatever_of :attr
macros do is call validates :attr, :whatever => true
.
The problem is you are using validate
and not validates
.
回答2:
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
回答3:
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)
回答4:
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