Rails 3:验证 :presence =>true 与 validates_presence_of [英] Rails 3: validates :presence => true vs validates_presence_of
问题描述
validates :presence
和 validates_presence_of
有什么区别?查看 ActiveModel
看起来他们以相同的方式设置验证.但是,鉴于以下模型定义:
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
对 Account
的实例调用 save 不会验证所有者的存在.不过,如果我使用 validates_presence_of
它会.
Calling save on an instance of Account
does not validate the presence of owner. Though, if I use validates_presence_of
it will.
推荐答案
所有那些 validates_whatever_of :attr
宏所做的就是调用 validates :attr, :whatever =>真的
.
All those validates_whatever_of :attr
macros do is call validates :attr, :whatever => true
.
这篇关于Rails 3:验证 :presence =>true 与 validates_presence_of的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!