【问题标题】:Unable to customize devise error message无法自定义设计错误消息
【发布时间】:2014-02-19 19:57:15
【问题描述】:

我正在使用 Devise 3.2.2,我想为我的自定义设计注册控制器自定义错误消息,如建议 here。传入已使用的电子邮件地址时,(自定义)控制器代码

if user.save
  render :json => user.as_json, :status => 201
else
  warden.custom_failure!
  render :json => user.errors, :status => 422
end

产生以下 json

{"email":["has already been taken"]}

我希望阅读此错误消息

{"messages": ["The email address has already been taken."]}

不幸的是,我在 config/locales/en.yml 文件中找不到字符串“已被占用”(我在 GitHub 上也没有看到它)。换句话说,建议的解决方案并不直接适用于手头的问题。

在哪里可以找到相关的错误消息?有没有一种干净的方法可以在我的自定义控制器中生成人类可读的错误消息数组?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 devise registration user-registration


    【解决方案1】:

    哇——RoR 第 n 次让我大吃一惊。什么框架。我喜欢它!

    所以,user.errors 只是一个 ActiveModel::Errors 对象。据我了解,有些错误是在 Devise gem 的语言环境中指定的。其他,如索引字段的唯一性等(如电子邮件字段),由 ActiveModel-validation 提供。这就是为什么我在 gem 语言环境中找不到给定错误的原因。

    现在; ActiveModel::Errors documentation 有一些很有趣的说法。它说有一个名为full_messages() 的方法“返回数组中的所有完整错误消息”。我的控制器现在看起来像这样:

    if user.save
      render :json => user.as_json, :status => 201
    else
      warden.custom_failure!
      render :json => { :messages => player.errors.full_messages }, :status => 422
    end
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 2011-08-15
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多