[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.

app/controllers/items_controller.rb


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

If you fail to save due to validation etc. in 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 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 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: ,

Updated: