【问题标题】:ActiveModel::Error : Is there a way to get the error type?ActiveModel::Error :有没有办法获取错误类型?
【发布时间】:2015-03-05 08:45:40
【问题描述】:

我想要实现的是获得失败的验证类型。是空白吗?复制 ?长度?

class Film <; ActiveRecord::Base
    validates :title, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
    validates :budget, :presence => true, :length => { :within => 1..10000000 }
end

我希望能够做到这一点

f = Film.create
f.errors.first.type = :presence

或者类似的东西。我想这样做以将失败的原因从我的 API 发送给 API 使用者(移动设备)。

{
   "errors": [{
      "code": "film_empty_title",
      "reason": "empty"
   }]
}

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    我在我的博客上发表了一篇关于如何做到这一点的帖子: https://pgord.wordpress.com/2015/02/19/quick-bit-reason-for-activerecord-rollback-in-the-rails-console/

    在你的情况下试试这个:

    f = Film.create
    f.errors.full_messages
    

    【讨论】:

    • 在这种情况下,我将得到一个字符串,该字符串在不同版本上可能会因多种原因发生变化。
    【解决方案2】:

    Rails 5 的这个反向移植怎么样:https://github.com/cowbell/active_model-errors_details

    【讨论】:

      【解决方案3】:

      使用.errors.on

      user = User.new
      user.valid?
      user.errors.on(:email)
        => "is not a valid email address.  Please check that you have typed or copied it correctly."
      user.errors.on(:last_seen_at)
        => nil
      

      因为这会返回一个字符串(真实)或 nil(虚假),所以您可以在类似的 if 测试中使用它

      if user.errors.on(:email)
        ...
      

      在你的情况下,如果你想创建一个错误的 json 字符串,我认为你可以简单地这样做:

      json = {:errors => film.errors}.to_json
      

      (注意我使用film而不是f作为变量名,使用描述性名称要好得多,并且“f”按照约定是用于存储表单的变量表单块)

      但对我来说,这给了我(使用我的用户示例)

      "{\"errors\":[[\"password_confirmation\",\"is too short (minimum is 4 characters)\"], [\"first_name\",\"is too short (minimum is 1 characters)\"], [\"last_name\",\"is too short (minimum is 2 characters)\"], [\"login\",\"can't be blank\"], [\"password\",\"is too short (minimum is 4 characters)\"], [\"email\",\"is not a valid email address.  Please check that you have typed or copied it correctly.\"]]}"
      

      这不是您所需要的——它将错误存储在一个数组而不是哈希中。

      试试这个:

      hash = {:errors => [{}]};film.errors.each{|f,m| hash[:errors][0][f] = m};hash
      

      然后您可以通过hash.to_json 获取实际响应内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 2010-11-05
        • 1970-01-01
        • 2020-02-17
        • 1970-01-01
        相关资源
        最近更新 更多