Rails 3: validates :presence => true vs validates_presence_of

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!