在rails活动记录验证中,除了错误消息外,是否还可以返回错误代码? [英] Is there a way to return error code in addition to error message in rails active record validation?

查看:79
本文介绍了在rails活动记录验证中,除了错误消息外,是否还可以返回错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails ActiveRecord验证中,通常如果验证失败,它将在模型的errors属性中添加一条错误消息,但是我们的客户要求除错误消息之外还返回错误代码,例如,我们有一个Bill模型,具有msisdn属性,如果msisdn为null,则错误代码为101;如果msisdn不投诉采用MSISDN格式,则当客户端通过REST接口提交请求并且验证失败时,错误代码为102。 ,我们应该返回一个json对象,例如

In rails activerecord validation, normally if a validation fails, it will add an error message in the errors attribute of models, however our clients demands an error code be returned in addition to error message, for example, we have a Bill model, which has a msisdn attribute, if msisdn is null, the error code is 101, if the msisdn doesn't complaint with MSISDN format, the error code is 102, when the client submits a request through REST interface, and if the validation fails, we should return a json object like

bill: {
    error_code: 101,
    error_message: "msisdn can't be null"
}

有没有办法告诉activerecord生成除错误消息外,还有错误代码?

Is there a way to tell activerecord to generate an error code in addition to error messages? Thanks a lot.

推荐答案

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

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.

这篇关于在rails活动记录验证中,除了错误消息外,是否还可以返回错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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