【问题标题】:Add prefix to devise error helper添加前缀以设计错误帮助程序
【发布时间】:2017-04-10 03:31:16
【问题描述】:

我的应用程序已正确配置了设计,并且助手正在努力在字段旁边显示单独的错误消息。目前,错误显示为“不能为空白”或“已被占用”。我想为其添加前缀,例如“用户名不能为空”或“电子邮件” 已经被拍了”,但不知道怎么拍。

这基本上是我想要实现但不起作用的目标

<%= "Username" + errors_for @user, :username %>

用户.rb

   def errors_for(model, attribute)
      if model.errors[attribute].present?
        content_tag :div, :class => 'error_explanation' do
          model.errors[attribute].join(", ")
        end
      end
    end

设计/注册/new.html.erb

<%= f.text_field :first_name, autofocus: true, class: 'form-control', placeholder: 'First name' %>
  <%= errors_for @user, :first_name %>
  <br>
  <%= f.text_field :username, autofocus: true, class: 'form-control', placeholder: 'Username'%>
  <%= errors_for @user, :username %>
  <br>

【问题讨论】:

    标签: ruby-on-rails devise


    【解决方案1】:

    您可以通过以下方式获取完整消息:

    @user.errors.full_messages_for(:first_name)
    @user.errors.full_messages_for(:username)
    

    或者使用

    @user.errors.full_messages
    

    获取所有完整的错误消息。

    您可以更改语言文件中的模型字段名称和错误消息:config/locales/**.yml(在devise 范围内。)

    示例:如果您的应用语言是英语,请编辑您的 config/locales/en.yml

    en:
      activerecord:
        attributes:
          user:
            first_name: "your custom field name"
        errors:
          messages:
            blank: "your custom error message"
    

    您可以从here获取更多信息。

    希望这会有所帮助。

    【讨论】:

    • 谢谢,这可行,但我得到 ["First name can't be blank"] 并想删除 [" "] 并设置错误消息的样式。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2018-09-11
    • 2011-09-09
    • 2016-01-08
    • 1970-01-01
    相关资源
    最近更新 更多