如何显示一次一个的Ruby on Rails表单验证错误消息 [英] How to display Ruby on Rails form validation error messages one at a time
问题描述
这允许每个字段每次显示1个错误。这几乎是我想要做的,但不完全是。我想一次显示1个错误信息。例如。名字不能为空。一旦解决了它,就会进入下一个错误。所以,如果用户将数字添加到他们的姓氏,它不会再是空白,但它会显示另一个错误,说明只有字母被允许等。当该错误被修复时,它会去姓氏错误或可能电子邮件,如果用户字段
<%@ user.errors.each do | attr,msg | %GT;
<%=#{attr}#{msg}if @ user.errors [attr] .first == msg%>
<%end%>
经过几个小时的试验,我找到了答案。
<%if user.errors.full_messages.any? %GT;
<%@ user.errors.full_messages.each do | error_message | %GT;
<%= error_message if @ user.errors.full_messages.first == error_message%> < br />
<%end%>
<%end%>
更好:
<%= @ user.errors.full_messages.first if @ user.errors.any? %GT;
I'm trying to understand how I can achieve this. Can anyone advise me or point me in the right direction?
This allows 1 error from each field to display at a time. It is nearly what I want to do but not quite exactly. I want to display 1 whole error message at a time. E.G. first name can't be blank. Once that has been resolved it moves onto the next error. So if the user added numbers to their last name it wouldn't be blank any more but it would show another error stating only letters were allowed etc. When that error was fixed it would go to last name error or maybe email if the user field out their last name correctly.
<% @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 %>
Even better:
<%= @user.errors.full_messages.first if @user.errors.any? %>
这篇关于如何显示一次一个的Ruby on Rails表单验证错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!