Rails foundationSort Order

Rails: Handling Validation Errors

In this episode we show you how to render the validation errors in the view, so we can inform our users how to correct their actions so they can proceed in our application.

We can look into the @user object to see how the errors are tracked.

class UsersController < ApplicationController  # ...  def create    @user = User.nnew(user_params)    if @user.save      redirect_to root_path    else      # add binding.bry so we can pause execution      binding.pry      render :new    end  end  # ...end

Once we pause the execution we can look into the object to see what we get from the validation error.

@user.errors.messages#=> {:email => ["is invalid"]}@user.error.full_messages#=> ["Email is invalid"]@user.error.count#=> 1

We can use this to render out the errors in the views.

# app/views/users/new.html.erb<%= form_for @user do |f| %>  <% if @user.errors.any? do %>    <div class='alert alert-danger'>      <h3>        <%= pluralize(@user.error.count, 'error') %> stopped this form from saving.      </h3>            <ul>        <% @user.error.full_messages.each do |message| %>          <li>            <%= message %>          </li>        <% end %>      </ul>    </div>  <% end %><% end %>

At this point if we submit the form with errors again it should show up in the alert box.