[Ruby] Get error message using any? method

1 minute read

I would like to summarize the method used when displaying the error message.

What is the ##any? method?

The any? method returns false if all elements are false. Immediately returns true if any element is true.

The way to write is like this

p [false, nil].any? # => false

For example, suppose that the description of the error message is described in the partial template and that it is set to be displayed only when the object has error information.


def create
    @item = Item.new(item_params)
    if @item.save
      redirect_to root_path
      render :new

If you fail to save due to validation etc. in this description Set to return to the new action.


  <%= form_with model: @item, local: true do |f| %>
      <%= render'shared/error_messages', model: @item %>

Bring the model object with error information to the render destination.


<% if model.errors.any? %>
<div class="error-alert">
    <% model.errors.full_messages.each do |message| %>
    <li class='error-message'><%= message %></li>
    <% end %>
<% end %>

Check the contents of errors with the any? method, and if it exists, it will be true and error repeat processing will work.

It’s also very similar to the present? method, but the any? method

In the above example, the error message is displayed by repeating the process.

If you want to display an error message for each label location, you can use the include? method.

Tags: ,