【问题标题】:Rails 3 - get full error message for one fieldRails 3 - 获取一个字段的完整错误消息
【发布时间】:2012-04-07 22:18:42
【问题描述】:

我有user.errors,它给出了我的控制器中的所有错误。所以,我有字段:user_login,它有错误。我如何才能从user.errors 获得完整 错误消息,仅针对该字段?

我可以像这样得到这个字段的文本:

user.errors[:user_login] # Gives that 'can't be empty'

但我真的很想做这样的事情

user.errors.get_full_message_for_field[:user_login] # 'Your login can't be empty'

【问题讨论】:

  • Quv's answer below 现在似乎是最好的选择。可能值得切换接受的答案@ExiRe?

标签: ruby-on-rails ruby model-view-controller controller


【解决方案1】:

嗯,我知道这个问题是在一年半前针对 Rails 3.x 明确发布的,但现在 Rails 4.x 似乎拥有您想要的方法,full_messages_for

user.errors.full_messages_for(:user_login) #=> return an array
# if you want the first message of all the errors a specific attribute gets,
user.errors.full_messages_for(:user_login).first
# or
user.errors.full_messages_for(:user_login)[0]

它比以前使用的user.errors.full_message(:user_login, user.errors[:user_login].first) 更简洁。

【讨论】:

    【解决方案2】:

    在这里查看full_message

    http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_message

    有点冗长,但您可以执行以下操作:

    user.errors.full_message(:user_login, user.errors[:user_login])
    

    【讨论】:

    • 实际上必须更像这样:resource.errors[:user_login].map { |error| user.errors.full_message(:user_login, error) }
    【解决方案3】:
    We can get the error message of particular field by using
    
    <%= resource.errors.full_messages_for(:email).join("") %>
    
    output : Email cant be blank
    
    If you want to check the particular field has error or not then check it by using
    
    resource.errors.include?(:email)
    
    output : true/false
    

    【讨论】:

    • 很适合使用full_messages_for。顺便检查一下特定字段是否有错误,我们也可以使用它resource.errors[:field].any?
    【解决方案4】:

    这里是代码 sn-p,用于仅显示每个字段的第一个错误。

    <!-- Display only first error for each field --->
    <% entity.attributes.keys.each do |key| %>
        <% if entity.errors.full_messages_for(key.to_sym).length > 0 %>
            <li><%= entity.errors.full_messages_for(key.to_sym).first %></li>
        <% end %>
    <% end %>   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多