有效是false但错误为空

时间:2014-03-13 09:08:11

标签: ruby-on-rails

当我检查对象是否有效<%= 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'

1 个答案:

答案 0 :(得分: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