零的 ActiveRecord 验证 [英] ActiveRecord validation for nil

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

问题描述

我正在尝试编写一个允许任何字符串但不允许 nil 的活动记录验证.

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

validates_presences_of 的问题在于它返回 false 为"或",我认为它是有效的.

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

我也尝试过 validates_length_of :foo, :minimum => 0 没有用

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

我也试过 validates_length_of :foo, :minimum => 0, :unless => :nil?这也不起作用.这两个都允许设置 nil 值并且验证仍然返回 true.

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.

推荐答案

validate :blank_but_not_nil

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

这篇关于零的 ActiveRecord 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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