Growl Notifications for Form Validations in Rails
In the last guide we implemented Growl notifications, but it did not work for all of the form validations. In this guide we are going to fix that.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In the last guide we implemented Growl notifications, but it did not work for all of the form validations. In this guide we are going to fix that.

Open the _form.html.erb partial and insert some debugging code in the second line, like this:

<!-- app/views/posts/_form.html.erb -->

<%= @post.errors.inspect %>

Start the rails server and open your browser. When you try to create a post, you'll get this message:

large

It says that the date and rationale fields cannot be empty. To have this message displayed as a Growl notification we need integrate our alert call into our form.

<!-- app/views/posts/_form.html.erb -->

<%= form_for @post, class: "form-horizontal" do |f| %>
  <%= @post.errors.inspect %>

  <% @post.errors.each do |error| %>
    <%= js add_gritter(error, title: "Overtime App Notification", sticky: false) %>
  <% end %>

This may seem like it will work, however we're making a few mistakes here that are important to understand. When you refresh the page, and save without entering the values, it throws an error.

large

The two problems here are:

  1. We need to first check to see if there are errors. If we attempt to loop over a set of messages that don't exist the page is always going to throw an error.
  2. Next, we need to loop over the full_messages method call provided by Devise, not the error objects themselves.

In order to get this working let's update the code as follows:

<!-- app/views/posts/_form.html.erb -->

<%= form_for @post, class: "form-horizontal" do |f| %>

  <% if @post.errors.any? %>
    <% @post.errors.full_messages.each do |error| %>
      <%= js add_gritter(error, title: "Overtime App Notification", sticky: false) %>
    <% end %>
  <% end %>

If you refresh the browser you'll see that now the system is showing the notifications properly.

large

Resources