Attribute name showing on Devise Error

2019-09-17 10:29发布

问题:

I'm trying to customize my devise error messages however the attribute name is always being included on the message.

I've already changed my en.yml file:

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            password:
              blank: "Error"
      full_messages:
        format: "%{message}"

devise_helper.rb

module DeviseHelper
  def devise_error_messages!
    return "" if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t("errors.messages.not_saved",
                      count: resource.errors.count,
                      resource: resource.class.model_name.human.downcase)

    html = <<-HTML
      <div id="error_explanation">
      <h2>#{sentence}</h2>
      <ul>#{messages}</ul>
      </div>
      HTML
    html.html_safe
  end
end

So for example on the code above the error message that displays is "Password Error" when I only wanted to display "Error"

回答1:

You are calling full_messages method in the overridden devise_error_messages! of your devise helper. full_messages method prepends attribute name to the validation error message.

Replace

messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join

with

messages = resource.errors.messages.map { |attr,msg| content_tag(:li, msg.join(', ')) }.join

See my answer for this SO question to get a better idea.



回答2:

You should use

en:
  errors:
    format: "%{message}"