简体   繁体   English

如何使用Devise在Rails中进行错误消息插值?

[英]How to do Error Message Interpolation in Rails with Devise?

I have a Rails 3.2 app running with Devise 2.3. 我有一个运行Devise 2.3的Rails 3.2应用程序。 I kept the email address as the default authentication key. 我将电子邮件地址保留为默认身份验证密钥。 When a user tries to create a new account with an existing email address, I would like to show him links to the login and to the reset password pages. 当用户尝试使用现有电子邮件地址创建新帐户时,我想向他显示指向登录名和重置密码页面的链接。

There is an answer to another question that suggests how to proceed with this in Rails, but it doesn't solve the problem when using Devise. 另一个问题答案 ,建议如何在Rails中进行此操作,但是使用Devise时并不能解决问题。 When trying to define a custom validation on the email, the server won't even start. 尝试在电子邮件上定义自定义验证时,服务器甚至无法启动。 See the pastebin . 参见pastebin

Is there a way I can override or hijack the error message added by Devise to use my own instead? 有没有一种方法可以覆盖或劫持Devise添加的错误消息以改用我自己的错误消息? Or is there a way to add global interpolation values? 还是有一种添加全局插值的方法?

This is the message I would like to show: 这是我想显示的消息:

  taken: email already used, please <a href='%{login_link}'>login</a> or <a href='%{reset_link}'>reset your password</a>

The app tries to display it, but complains about the missing interpolation keys. 该应用尝试显示它,但抱怨缺少插值键。 How I can assign the interpolation keys with Devise already handling the validation on the email? 如何使用已在电子邮件上进行验证的Devise分配插值键?

This may not be the canonical example of this problem, since application links are fairly static and hard-coding would be okay here. 这可能不是此问题的典型示例,因为应用程序链接是相当静态的,并且在这里可以进行硬编码。 What if other truly dynamic values were to be interpolated? 如果要插值其他真正的动态值怎么办?

Try passing these from the user.rb file 尝试从user.rb文件传递这些

validates :email, :uniqueness => {:login_link => Rails.application.routes.url_helpers.new_user_session_path, 
                                  :reset_link => Rails.application.routes.url_helpers.new_user_password_path}

AFAIK it is not possible as long as Devise's default validations are used by declaring the following on the authentication model: AFAIK是不可能的,只要通过在身份验证模型上声明以下内容来使用Devise的默认验证即可:

devise :validatable

In order to use error message variable interpolation in Rails with YAML locale files when using Devise, all validations have to be declared manually and the ones provided by Devise have to be deactivated. 为了在使用Devise时在带有YAML语言环境文件的Rails中使用错误消息变量插值,必须手动声明所有验证,并且必须停用由Devise提供的验证。

When trying to override a single existing validation, Rails 3.2 fails during initialization. 当尝试覆盖单个现有验证时,Rails 3.2在初始化期间失败。 So it's an all in or all out when using Devise validations. 因此,在使用Devise验证时,这是一个全过程或全过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM