2012-02-17 117 views
15

如何自定义错误消息覆盖的密码控制器?如何在密码更改时覆盖设计错误消息

class PasswordsController < Devise::PasswordsController 
    def create 
    self.resource = resource_class.send_reset_password_instructions(params[resource_name]) 

    if resource.errors.empty? 
     set_flash_message(:notice, :send_instructions) if is_navigational_format? 
     respond_with resource, :location => home_path 
    else 
     binding.pry 
     flash[:devise_password_error] = (resource.errors.map do |key, value| 
     value.capitalize 
     end).flatten.join('|') 
     redirect_to home_path and return 
    end 
    end 
    def edit 
    self.resource = resource_class.new 
    resource.reset_password_token = params[:reset_password_token] 
    end 
end 

resource.errors可用在该方法中,但它包含缺省消息,例如Email not foundEmail can't be blank和。我需要自定义此消息。我试图从我的用户模型中删除:validatable并添加自定义验证器,但这仅适用于从Devise :: RegistrationsController派生的自定义注册控制器,而不适用于自定义密码控制器。

有没有解决方法?

+0

你解决这个问题? – 2012-12-07 15:04:05

+0

我知道这是旧的,但检查[这个答案](http://stackoverflow.com/a/18578028/1964165)为更通用和干净的方法。 – akhanubis 2013-09-02 17:22:37

回答

7

制定消息位于配置/区域设置/ devise.en.yml

我不知道你想覆盖该消息,但是这就是你想这样做。

+3

我想要覆盖的消息不在那里。我想更改的这些消息是验证失败时使用的默认消息,'config/locales/devise.en.yml'包含设计信息消息。 – RomanKapitonov 2012-02-17 16:11:52

+0

这些消息确实不在那里,但您可以添加它们,它会起作用。看到我上面的答案。 – Justin 2013-12-11 23:28:35

0

它的效果并不理想,但基于this related ticket我已经得到它具有以下工作(我知道是一个黑客位,但它的工作原理):

module DeviseHelper 
    def devise_error_messages! 
    resource.errors.full_messages.map { |msg| msg == 'Email not found' ? 'The email address you entered could not be found. Please try again with other information.' : msg }.join('<br/>') 
    end 
end 

一个名为模块将这个devise_helper.rb/app/helpers目录

15

答案是修改配置/区域设置/ devise.en.yml,但你必须添加的设置,它们不存在默认情况下。

en: 
    activerecord: 
    errors: 
     models: 
     user: 
      attributes: 
      password: 
       confirmation: "does not match" 
       too_short: "is too short (minimum is %{count} characters)" 

信用此去Vimsha谁,我几乎回答了同样的question

+1

您应该在错误消息中使用%{count},而不是硬编码最小值。 count由范围验证器传递给I18n.t,因此将始终与设计设置相匹配。 – ReggieB 2015-02-16 09:08:04

0

添加到您的routes.rb

devise_for :users, controllers: { passwords: 'passwords' } 

devise_for :users, :controllers => { :passwords => 'passwords' }