rails 字符串长度验证不起作用 [英] rails string length validation not working

查看:39
本文介绍了rails 字符串长度验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定遗漏了一些基本的东西,但我不断收到验证错误:

I must be missing something basic but I keep getting validation errors:

app/model/person.rb

app/model/person.rb

class Person < ActiveRecord::Base
  attr_accessible  :cell

  before_validation :format_cell_string

  validates :cell, :length => { :is => 10 }

  protected

    def format_cell_string
      self.cell = self.cell.gsub!(/\D/, '') if self.cell != nil
    end

end

在轨道 c

> bib = Person.new(cell: "1234567890")
> bib.save

导致回滚

bib.errors<代码>=>#<ActiveModel::Errors:0x007fcb3cf978d8 @base=#<Person id: nil, created_at: nil, updated_at: nil, cell: nil>, @messages={:cell=>["是错误的长度(应该为 10 个字符)"]}>

认为这可能是 rails 控制台或 irb 错误,我也尝试在我的表单中无济于事.尝试 bib = Person.new, bib.save 然后 bib.update_attributes(cell: "0123456789") 在控制台中也不起作用.我是不是错过了什么!我已经检查了 rails docs on validationrails api 关于模型验证 并尝试了许多不同的事情.有什么想法吗?我使用的是 rails 3.2.6,刚刚升级到 rails 3.2.7.没有变化.

Thinking that is could be a rails console or irb error, I also tried in my form to no avail. Trying bib = Person.new, bib.save and then bib.update_attributes(cell: "0123456789") also doesn't work in the console. Am I missing something! I've check the rails docs on validations and the rails api on model validations and tried many different things. Any thoughts? I was using rails 3.2.6 and just upgraded to rails 3.2.7. No change.

推荐答案

gsub! 就地修改字符串并返回 nil 如果未进行任何更改:

gsub! modifies the string in place and returns nil if no changes were made:

"1234567890".gsub!(/\D/, '') #=> nil

因此,在该字段仅包含数字的情况下,您的代码会在验证之前将该字段设置为 nil,这会导致它失败.通常最好避免在属性上使用 gsub! ,因为它不能很好地与 Rails 的更改跟踪配合使用.

So in the case where the field contains only digits your code is setting the field to nil before the validation which causes it to fail. Using gsub! on attributes is best avoided generally, as it doesn't play well with Rails' change tracking.

self.cell = self.cell.gsub(/\D/, '') if self.cell != nil

应该做的伎俩

这篇关于rails 字符串长度验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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