whysthatso

Check For Custom Errors In Rails Error Objects

Posted on May 10, 2025  //  rails

In a view one can usually do something like this to check if there is an error after a validation and then conditionally change some design, for example:

<% if course_registration_form.errors[:email].any? %>
	<%= content_tag(:p, course_registration_form.errors[:email].first, class: "mt-2 text-sm text-red-600") %>
<% end %>

however, if you have a custom validation that groups errors on an arbitrary key that is not backed by an object’s attribute, you have to query differently:

<% if course_registration_form.errors.where(:person_info).any? %>
	<%= content_tag(:p, course_registration_form.where(:person_info).map(&:message), class: "mt-2 text-sm text-red-600") %>
<% end %>

Hey! I'll happily receive your comments via email. Thanks for reading.

Andreas Wagner
freelance System Administrator and Ruby programmer in Tallinn, Estonia