【问题标题】:Devise, customizing the error messages?设计、定制错误消息?
【发布时间】:2012-02-22 01:20:31
【问题描述】:

我正在使用带有设计的 rails 3。

我有一个包含字段的用户表:电子邮件、密码、fname、lname

我目前在我的视图中输出错误如下:

<% if @user.errors.any? %>
    <div id="error_explanation" class="error">
    <h2>Hold on!</h2>
        <ul>
            <% @user.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
<% end %>

问题是这样呈现为:

Email The User's Email cannot be blank
Password The User's Password cannot be blank
Fname The User's Fname is too short (minimum 1 characters)
Lname The User's Lname is too short (minimum 1 characters)

如何让每个错误都不首先出现字段名称?

在我的用户模型中,我有:

验证 :fname, :length => { :minimum => 1, :maximum => 100 } 验证 :lname, :length => { :minimum => 1, :maximum => 100 }

我可以使用消息属性自定义这些字段。似乎内置于设计中的电子邮件和密码呢?如何自定义这些错误消息?

谢谢

【问题讨论】:

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


    【解决方案1】:

    http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

    validates_presence_of(*attr_names)
    
     Configuration options:
      message - A custom error message (default is: "can‘t be blank").
    

    至于内置名称自定义,这个帖子可以提供帮助

    Rails3: Devise internationalization does not localize "Password confirmation" and others

    (扩展)

    activerecord:
       attributes:
           user:
            email: "your_way_of_email"
              password: "your_way_of_password"
              password_confirmation: "your_way_of_password_confirmation"
    

    Rails 会humanize他们

    【讨论】:

      【解决方案2】:

      使用 each_key 检索字段并导航每个字段上的错误。

      <% if @user.errors.any? %>
          <div id="error_explanation" class="error">
          <h2>Hold on!</h2>
              <ul>
                  <% @user.errors.each_key do |attr| %>
                      <% @user.errors[attr].each do |msg| %>
                          <% next if msg.nil? %>
      
                          <li><%= msg %></li>
                      <% end %>
                  <% end %>
              </ul>
          </div>
      <% end %>
      

      查看full_messages的来源: http://ar.rubyonrails.org/classes/ActiveRecord/Errors.html#M000311

      【讨论】:

      • 这只是显示电子邮件密码 fname lname ...我想要另一边:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      相关资源
      最近更新 更多