ActiveRecord validation for nil

孤者浪人 提交于 2019-12-08 09:38:24

问题


I am trying to write an active record validation that allows any string but does not allow nil.

The problem with validates_presences_of is that it returns false for "" or " " which I want to consider valid.

I have also tried to do validates_length_of :foo, :minimum => 0 which did not work

I have also tried t o do validates_length_of :foo, :minimum => 0, :unless => :nil? which also did not work. Both of these allowed for nil values to be set and the validation still returns true.

Am i missing something here? I feel like it shouldnt be this hard to simply validate that the element is not nil.


回答1:


validate :blank_but_not_nil

def blank_but_not_nil
   if self.foo.nil?
     errors.add :foo, 'cannot be nil'
   end
end



回答2:


Can you try:

validates_length_of :foo, :minimum => 0, :allow_nil => false

For example:

User < ActiveRecord::Base
  validates_length_of :name, :minimum => 0, :allow_nil => false
end

> u=User.new
> u.valid?  #=> false  #u.name is nil
> u.name=""
> u.valid?  #=> true


来源:https://stackoverflow.com/questions/14737030/activerecord-validation-for-nil

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