【问题标题】:Customizing Devise error messages in Rails 3?在 Rails 3 中自定义设计错误消息?
【发布时间】:2011-08-15 21:27:50
【问题描述】:

我正在使用设计来处理身份验证。总的来说我喜欢它,但我想稍微自定义一下错误显示。现在我的观点如下。

<div class="field <% if resource.errors[:email].present? %>error<% end %>">
  <%= f.label :email, "Email:" %><br />
  <% if resource.errors[:email].present? %>
    <ul>
      <% resource.errors[:email].each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  <% end %>
  <%= f.text_field :email, :class => "text" %>
</div>

但是当邮件出现问题时,显示的信息如下:is invalid。这不是很用户友好,但我找不到设置此消息的位置。它似乎不在 devise.en.yml 中,但也许我忽略了一些东西。

知道在哪里可以自定义错误消息吗?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 devise


    【解决方案1】:

    您可以在以下位置的语言环境文件中配置错误消息:/config/locales/devise.en.yml

    应该有类似下面的代码,你可以根据自己的喜好轻松修改:

    en:  
      errors:  
        messages:  
          not_found: "not found"  
          already_confirmed: "was already confirmed"  
          not_locked: "was not locked"  
    
      devise:  
        failure:  
          unauthenticated: 'You need to sign in or sign up before continuing.'  
          unconfirmed: 'You have to confirm your account before continuing.'  
          locked: 'Your account is locked.'  
          invalid: 'OH NOES! ERROR IN TEH EMAIL!'  
          invalid_token: 'Invalid authentication token.'  
          timeout: 'Your session expired, please sign in again to continue.'  
          inactive: 'Your account was not activated yet.'  
        sessions:  
          signed_in: 'Signed in successfully.'  
          signed_out: 'Signed out successfully.'  
    

    如需更详细的说明,请查看url(附截图)。文章中的自定义错误消息部分。

    【讨论】:

    • 感谢您的建议。正如我在原始问题中指出的那样,我看到的错误消息不在语言环境文件中。不过,RobZolkos 的回答让我走了。谢谢!
    【解决方案2】:

    如果您想更改设备添加的海关验证消息,请查看Christian's answer

    否则,如果您要自定义的验证是标准验证(如电子邮件格式),则无需删除设计验证并将其替换为您自己的验证。处理此问题的更好方法是使用Rails guides 中列出的默认错误消息优先级,并覆盖特定字段和特定验证的错误消息。

    对于这个特定的问题,您需要在 config/locales/en.yml 中添加以使用自定义电子邮件错误消息更改 is invalid 的键是 activerecord.errors.models.user.attributes.email.invalid(其中 user 是模型的名称):

    en:
      activerecord:
        errors:
          models:
            user:
              attributes:
                email:
                  invalid: "custom invalid message"
    

    Rails 将按以下顺序搜索要显示的消息以进行验证:

    activerecord.errors.models.[model_name].attributes.[attribute_name]
    activerecord.errors.models.[model_name]
    activerecord.errors.messages
    errors.attributes.[attribute_name]
    errors.messages
    

    【讨论】:

    【解决方案3】:

    这些验证都在validations 模块中定义,并使用默认的Rails 错误消息。

    您可以在模型中覆盖这些。

    validates_format_of :email, :with=>email_regexp, :allow_blank => true, :message=>"new error message here" 
    

    【讨论】:

    • 谢谢!还值得注意的是,为了使其工作,您需要从模型中删除 :validatable 并将所有验证转移到模型中。
    • Rails 无需重写 Devise 验证即可完成它的方法是 here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多