[RUBY] How to put out the error bundling

【Overview】

1. Conclusion </ b>

2. How to put out the error bundling </ b>

3. Where it gets stuck </ b>

  1. Conclusion

Use validates </ b>, .errors.any </ b> and .errors.full_messages.each </ b>!

  1. How to put out the error bundling

First, set the validation on the model!

app/models/buy_item


  with_options presence: true do
    validates :name
    validates :date
 end

With_options allows you to set presence: true (blanks are not allowed) from do to end on one side. In this case, the blanks in the name column and date column are set to be useless!

And in the controller, it is as follows.

controllers/buy_items_controller.rb


 def create
    @buy_item = BuyItem.new(buy_item_params)
    if @buy_item.save
      redirect_to root_path
    else
      render :new
    end
  end

If it is saved, it will move to the top page. If something is wrong and it is not saved, render will jump to new in the view. Because I want to do the following.

views/buy_items/new.html.erb


 <%= render 'public/error_messages', model: f.object %>

By doing this, when you jump to the new view of buy_items (render: new), you will be taken to the program for which the error display is set. f.object is | f | of @buy_item set in form_wtih, and the contents of @buy_item are taken out!

The contents (error sentences) of'public / error_messages' are as follows.

view/public/_error_messages


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

I'm using model because I'm using user in addition to the buy_item model. You can apply validation error content to all models. In addition, each error content is extracted by each method and displayed by <% = message%>!

The URL below helped me a lot!

Reference URL: How to issue Rails error message Validation error

  1. What I learned from here (used in case of error)

I changed the model to @user or @buy_item, and I didn't get the @user error or the NameErrormethod occurred, which made me confused. In addition, f.object was also made into an instance variable without permission, causing an extra error. Also, if you have two controllers and want to display with the index of the specified controller, you can use render "controller name / action name". However, since it is only displayed, it was a blind spot that I had to describe the data inside.

Recommended Posts