01 January 2015

What are ActiveRecord Error Messages?

ActiveRecord error messages inform end users of validation errors. If a user tries to submit data that fails the model validiations then an error message will be generated.

Rails makes it easy to let users know they need to get their act together!

How do ActiveRecord Error Messages Work?

When update is called on a model, ActiveRecord checks the data being persisted against any validations model validations. If model validations fail, then the object we attempted to persist will have error messages attached to it by ActiveRecord. Those error messages can be accessed with the following syntax:

model_object.errors.full_messages

This will provide a set of descriptive error messages. Those error messages can be iterated through and displayed:

app/controllers/users_controllers.rb

  current_user.update(some_attribute: some_value)

app/views/users/edit.html.erb

  <% if current_user.errors.any? %>

   <h1><%= pluralize(current_user.errors.count, ‘Error’) %> 
   <% current_user.errors.full_messages.each do |error| %></h1>
     <h2><%= error %></h2>
   <% end %>
  <% end %>

What are Non-ActiveRecord Error Messages?

Non-ActiveRecord error messages can be rather than using the system supplied by ActiveRecord. These are called flash messages.

How do Non-ActiveRecord Error Messages Work?

When update is called on a model, either true or false is returned. As one would expect, true indicates a successful update, as where a return value of false would indicate a failed update. The boolean return value can be used to let us know if their was a validation failure.

app/controllers/users_controllers.rb

  def update
    if current_user.update(user_params)
      flash[:notice] = "Update Successful"
    else
      flash[:notice] = "Update Failed"
    end
    redirect_to "/"
  end

app/views/layouts/application.html.erb

  

<%= flash[:error] %>