Sorting or error reporting in error_messages (Rails)
Is there any (easy) way to gain some control over the order in which model errors appear in the view? Usually, the order of the rules doesn't help.
Use error_message_on
instead error_messages
to get the message for an individual attribute.
<div class="errorMessages">
<% %{name title description}.each do |att| %>
<%= f.error_message_on att, :css_class => "error" %>
<% end %>
</div>
In 2.3.6, validation messages will be displayed for you to declare in code
link
Here's an answer (for my own notes, mostly) using Baldu's answer. This puts the attributes in alpha order:
<% if @model.errors.length>0 %>
<div class="errorExplanation">
<h3>There were problems with the following fields:</h3><ul>
<% @model.attribute_names.each do |attribute| %>
<% if !@model.errors[attribute].blank? %>
<li><%= f.error_message_on attribute, Model.human_attribute_name(attribute)+ " ", :style=>"display:inline" %></li>
<% end %>
</ul>
<% end %>
</div>
<% end %>
Of course, you can parameterize this further as partial, for example. I'll probably do it :)
I had the same problem in groovy in grails. changing it in the code doesn't change anything, the above answer doesn't work for me either. This is how I end up solving my problem. The command has created a custom tag to sort / arrange grails error messages.
def renderOrderedErrors = { attrs, body ->
def bean = attrs.bean
def fields = attrs.fields
fields.each { out << g.renderErrors(bean: bean, field:it) }
}
and this is how you use it:
<g:if test="${totalRating.hasErrors() || rating.hasErrors()}">
<div class="errors">
<g:if test="${totalRating.hasErrors()}"><g:renderOrderedErrors bean="${totalRating}" as="list" fields="${['totalEffectiveDate','awardedDisability']}"/></g:if>
<g:if test="${rating.hasErrors()}"><g:renderOrderedErrors bean="${rating}" as="list" fields="${['ratingStatus','ratingIssue','disability','effectiveDate','ratingType','socDate','nodDate','ssocDate','form9Date','six46Date','remandDate']}"/></g:if>//this is the way you want to order the fields in the form
</div>
</g:if>