Rails 3:验证 :presence =>true 与 validates_presence_of [英] Rails 3: validates :presence => true vs validates_presence_of

查看:63
本文介绍了Rails 3:验证 :presence =>true 与 validates_presence_of的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

validates :presencevalidates_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆