加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – Rails 3:如何验证以允许空格(“”),但不能

发布时间:2020-12-16 20:19:56 所属栏目:百科 来源:网络整理
导读:在ActiveRecord(或ActiveModel)中,我希望通过以下规范 it { should allow_value("").for(:my_string) }it { should_not allow_value(nil).for(:my_string) } 我努力了 validates :my_string,{ :length = { :in = 0..255 },:presence = true,:allow_blank = t
在ActiveRecord(或ActiveModel)中,我希望通过以下规范
it { should allow_value("").for(:my_string) }
it { should_not allow_value(nil).for(:my_string) }

我努力了

validates :my_string,{
  :length => { :in => 0..255 },:presence => true,:allow_blank => true,:allow_nil => false,}

并且

validates :my_string,}

但是,它既允许“”也不允许,或者没有.

解决方法

您可能需要为此进行自定义验证:
validates :my_string,:length => { :in => 0..255 }
validate :my_string_is_valid

def my_string_is_valid
  self.errors.add :base,'My string can not be nil' if self.my_string.nil? 
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读