Performance: Error messages and display
This affects page load speed and interaction responsiveness by how error messages are rendered and updated in the UI.
Render error messages inline next to each input field using small containers that update only changed parts. <%= form_with model: @user do |f| %> <div> <%= f.label :email %> <%= f.text_field :email %> <% if @user.errors[:email].any? %> <span class="error-message" role="alert"><%= @user.errors[:email].first %></span> <% end %> </div> <% end %>
In the view, render all error messages inside a large container that is hidden by default and shown by toggling CSS display, causing full reflow. <% if @user.errors.any? %> <div id="error_explanation" style="display:block;"> <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2> <ul> <% @user.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Toggling large error container visibility | Modifies one large container node | 1 full reflow triggered | High paint cost due to large area | [X] Bad |
| Inline error message updates next to inputs | Modifies small inline nodes | Localized reflow only | Low paint cost | [OK] Good |
@model.errors.full_messages returns an array of readable error strings, while others return metadata or counts.full_messages gives clear, complete error messages suitable for display.@user model in a Rails view?<% %> runs Ruby code without output; <%= %> outputs the result. For loops, use <% %>.<% @user.errors.full_messages.each do |msg| %> <%= msg %>
<% end %> correctly uses <% %> to loop and <%= %> inside to output each message.<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>@post.errors.full_messages contains ["Title can't be blank", "Content is too short"]?<%= @article.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %><%= %>each, which is the original array, not the loop content.<% %> for loops to run code without output, then use <%= %> inside for each message.@comment model. Which is the best way to do this in a Rails view?errors.any? to check if there are any errors to display.div with role='alert' and aria-live='assertive' for screen readers to announce changes.full_messages inside a ul with li for each error message.Pass the test and this pattern moves unknown