【问题标题】:Valid is false but errors empty有效为假但错误为空
【发布时间】:2014-03-13 09:08:11
【问题描述】:

当我检查对象是否有效<%= current_user.contact.valid? %> 它返回false。但是<%= current_user.contact.errors.count %> 返回0。我发现 solution 对某些人有用,但我不确定它是否适合我。

Contact 的验证

validates :RPNumber, :RPSerial, :RPNumber, :RPWho, :RPWhen, :RPDivisionCode,
            :Name, :RPDateBorn, :RPWhereBorn, :RPAddress, :RPFamilyStatus, :RPChild,
            :ZPNumber, :ZPWhereBorn, :ZPWhen, :ZPWhenEnd, :ZPWho, :GenderID, :ZPFIO, presence: true

  validates_format_of :ZPFIO, with: /^[a-zA-Z\s\-]*$/, message: 'ZPFIO'
  validates_format_of :Phone, with: /7\(\d+\)\d+/, message: 'Phone'
  validates_format_of :PhoneCode, with: /\d+/, message: 'PhoneCode'
  validates_format_of :PhoneNumber, with: /\d+/, message: 'PhoneNumber'
  validates_format_of :Web, with: /^(http|https)\:\/\/([a-z0-9][a-z0-9_-]*(?:.[a-z0-9][a-z0-9_-]*)+):?(d+)?\/?$/i, allow_blank: true, message: 'Web'
  validates_format_of :Mail, with: /^([0-9a-z]*([-|_]?[0-9a-z]+)*)(([-|_]?)\.([-|_]?)[0-9a-z]*([-|_]?[0-9a-z]+)+)*([-|_]?)@([0-9a-z]+([-]?[0-9a-z]+)*)(([-]?)\.([-]?)[0-9a-z]*([-]?[0-9a-z]+)+)*\.[a-z]{2,4}$/i, message: 'Mail'

【问题讨论】:

  • 你应该发布Contact模型的代码(或者如果它是一个大类,至少是与验证相关的代码)......
  • @Baldrick 添加了验证

标签: ruby-on-rails


【解决方案1】:

每次您执行current_user.contact 时,您都会创建一个新的联系人对象。所以,你正在做的是:

#make a new contact object and run validations on it
current_user.contact.valid?

#make a new contact object, which hasn't had validation run on it, then see if it has errors
current_user.contact.errors.count

试试这个:

contact = current_user.contact
contact.valid?
contact.errors.count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2013-11-17
    • 2012-12-29
    • 1970-01-01
    相关资源
    最近更新 更多