且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在rails活动记录验证中,除了错误消息外,是否还可以返回错误代码?

更新时间:2023-09-04 21:19:34

错误只是一个普通的哈希,键代表有错误的属性,值代表错误信息。因此从技术上讲,您的要求是可行的,方法是将文本消息替换为哈希。但是不利的一面是您可能需要做更多的事情才能以新格式显示错误。

errors is just a plain hash, with the key represents the attribute which has an error, and the value represents the error message. So technically your requirement is doable by replacing the text message with a hash. But the downside is you may need to do more things to show the errors in new format.

例如,使用自定义验证器添加错误代码

For example, use a custom validator to add error code

class Foo < ActiveRecord::Base
  attr_accessible :msiisnd
  validate :msiisdn_can_not_be_blank

  def msiisdn_can_not_be_blank
    if msiisdn.blank?
      errors.add(:msiisdn, {code: 101, message: "cannot be blank"})
    end
  end
end

然后使用它

foo = Foo.new
foo.errors.count
#=> 0
foo.valid?
#=> false
foo.errors.count
#=> 1
foo.errors[:msiisdn]
#=> [{ code: 101, message: "can not be blank"}]
foo.errors[:msiisdn][0][:code]
#=> 101

因此您可以使用它。但是当您需要正确显示错误时(例如,以表格形式显示错误),您需要做更多的工作,因为这不是惯例。

So you can use it. But you need to do more work when you need to show the errors correctly, say displaying errors in a form, as this is not a convention.