[RUBY] rails [Procedure for displaying an error statement when data transmission fails due to create action]

  1. Write the error statement in the view file you want to display. This time, write it in new.html.erb. 〇〇 is named by yourself.
<%= render '〇〇/error_messages', model: f.object   %> 

2.〇〇/_error_messages.html.erb Create and describe a file.

#〇〇/_error_messages.html.Contents of erb
<%if variable A.errors.any? %>
  <div id="error_explanation">
    <ul>
      <%Variable A.errors.full_messages.each do |message| %>
      <li class="error-alert"><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>
  1. If the data can be saved, the screen transitions to the index action of the same controller (items controller this time), and if it cannot be saved, the items # new action is displayed.
def create
    @item= Item.new(item_params)
     if @item.save
      redirect_to action: 'index'
    else
      render :new
    end
  end
  1. If data transmission fails with this new.html.erb <%= render '〇〇/error_messages', model: f.object %> An error statement will be displayed in the place where

Recommended Posts

rails [Procedure for displaying an error statement when data transmission fails due to create action]
[Rails] About the error when displaying the screen due to the autofocus of the form
No error message is displayed when create action fails
<Dot installation> What to do if you cannot proceed due to an error when building a development environment for Rails learning.
[Error resolution] Occurs when trying to build an environment for spring with docker
What to do if ffi installation fails when launching an application in Rails
When deploying to Heroku, OpenApp causes an error
Rails6.0 ~ How to create an eco-friendly development environment
After installing'devise''bootstrap' of gemfile with rails, what to do when url is an error
[Ruby on rails + Mysql] Data migration procedure memo when switching from heroku to AWS