【发布时间】:2014-07-03 10:38:57
【问题描述】:
我有这个模型
class User < ActiveRecord::Base
attr_accessible :type, :school_name, :school_grade
validates :type, :inclusion =>{:in =>['1','2']}, :allow_blank => true
validates :school_name, :presence =>{:if => :student?}
validates :school_grade, :numericality =>{:only_integer =>true}, :allow_blank => {:unless => :student?}
def student?
type.to_s == '1'
end
end
我尝试了以下模式。
User.create(:type =>'2', :school_name =>nil, :school_grade =>nil)
=> 好的。没有发生错误。
User.create(:type =>'1', :school_name =>nil, :school_grade =>1)
=> 好的。发生 ActiveRecord::RecordInvalid 错误“school_name is empty”。
User.create(:type =>'1', :school_name =>'foo', :school_grade =>'string is not a number')
=> 好的。出现验证错误“school_grade 不是数字”。
User.create(:type =>'1', :school_name =>'foo', :school_grade =>nil)
=> 不合格。我预计“school_grade is not a number”错误,但没有发生错误。
我也尝试过这种模式,但得到了相同的结果。
validates :school_grade, :numericality =>{:only_integer =>true}, :allow_blank => {:if => :not_student?}
def not_student?
type.to_s != '1'
end
我猜验证 :allow_blank 始终处于活动状态,但为什么呢?以及如何解决?
谢谢。
【问题讨论】:
-
数据库中
type的数据类型是什么?
标签: ruby-on-rails ruby-on-rails-3 validation activerecord