I would like to summarize the methods used to display the error message.
The any? method returns false if all elements are false. Immediately returns true if any element is true.
How to write is like this
p [false, nil].any? # => false
For example, suppose you write an error message description in a partial template and set it to be displayed only when the object has error information.
app/controllers/items_controller.rb
def create
@item = Item.new(item_params)
if @item.save
redirect_to root_path
else
render :new
end
end
When saving fails due to validation etc. with this description Set to return to the new action.
ruby:app/views/items/new.html.erb
<%= form_with model: @item, local: true do |f| %>
<%= render 'shared/error_messages', model: @item %>
Bring the model object with the error information to the render destination.
ruby:app/views/shared/_error_messages.html.erb
<% if model.errors.any? %>
<div class="error-alert">
<ul>
<% model.errors.full_messages.each do |message| %>
<li class='error-message'><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
Check the contents of errors with the any? method, and if it exists, it becomes true and the error is repeated.
Also quite similar to the present? method, but the any? method
In the above example, the error message is displayed by iterative processing.
If you want to display an error message for each label location, you can use the include? Method.
Recommended Posts