如何一次显示Ruby on Rails表单验证错误消息? [英] How do I display Ruby on Rails form validation error messages one at a time?

查看:73
本文介绍了如何一次显示Ruby on Rails表单验证错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解如何实现这一目标.谁能给我建议或指出正确的方向?

I'm trying to understand how I can achieve this. Can anyone advise me or point me in the right direction?

我当前正在做的事情,显示在下面的代码片段中,使我一次可以在每个字段中显示1个错误.这并不是我想做的完全正确.

What I currently do, which is shown in the code snippet below, allows me to display 1 error from each field at a time. It’s not not quite exactly what I want to do.

我想一次显示1条错误消息.例如,名字不能为空",然后解决该错误后,应显示错误数组中的下一个错误.在解决所有错误之前,这应该一直发生.

I want to display 1 error message at a time. For example, "first name can't be blank", then once that error has been resolved, the next error in the array of errors should be displayed. This should keep happening until all errors have been resolved.

<% @user.errors.each do |attr, msg| %>
<%= "#{attr} #{msg}" if @user.errors[attr].first == msg %> 
<% end %>

推荐答案

尝试了几个小时后,我才知道了.

After experimenting for a few hours I figured it out.

<% if @user.errors.full_messages.any? %>
  <% @user.errors.full_messages.each do |error_message| %>
    <%= error_message if @user.errors.full_messages.first == error_message %> <br />
  <% end %>
<% end %>

更好:

<%= @user.errors.full_messages.first if @user.errors.any? %>

这篇关于如何一次显示Ruby on Rails表单验证错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆