python
>> user = User.new
>> user.save #Error message generation
=> false
>> user.error.full_messages
=> [Failed"", "invalid"]
When saving an object, an error message is generated as an array element the moment false is returned.
erb
<% @user.errors.full_messages.each do |msg| %>
<%= msg %>
<% end %>
Each element of the array can be retrieved and displayed in each statement.
class="field_with_errors"
It automatically encloses the input parts of the error part.
While using partials, it is implemented so that it can handle any object.
ruby:shared/_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger alert-form-extend" role="alert">
<%= object.errors.count %>There are an error
</div>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
ruby:users/new.html.erb
<%= form_with(model: @user, url: users_path, local: true) do |form| %>
<%= render 'shared/error_messages', object: form.object %>
users_controller.rb
def create
@user = User.new(user_params)
if @user.save
~~
else
render 'new'
end
end
application.scss
#error_explanation {
color: red;
ul {
color: red;
padding-bottom: 0;
}
}
.field_with_errors .form-control {
border-color: red;
}