Error displaying a Rails form below each field

I have the following form

<%= form_for(@user) do |f| %> <% if @user.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2> <ul> <% @user.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <%= @user.errors.messages[:name] %> <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :email %><br> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :password %><br> <%= f.password_field :password %> </div> <div class="field"> <%= f.label :phone %><br> <%= f.text_field :phone %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> 

I want to display a form error for each field below it, and not just the entire top. Passed through the rail guide , but could not figure out how to do it.

+6
source share
1 answer

You can write a helper to return an error message for any field of any object

In /app/helpers/application_helper.rb :

 def show_errors(object, field_name) if object.errors.any? if !object.errors.messages[field_name].blank? object.errors.messages[field_name].join(", ") end end end 

In the view file:

 <div class="field"> <%= f.label :name %><br> <%= f.text_field :name %> <p class='error'><%= show_errors(@user, :name) %></p> </div> 
+10
source

Source: https://habr.com/ru/post/970036/


All Articles