Quantcast
Channel: rails – The Agile Warrior
Viewing all articles
Browse latest Browse all 48

How to add error messages top of rails page

$
0
0

Sometimes when I create views/controllers and models by hand I forget how rails gets error messages to appear at the top of a page.

Here is a reminder for myself for when I need to add these manually myself (by also extracting into a common pace a calling as follows).

application.html.erb

      <% flash.each do |key, value| %>
        <div class="alert alert-<%= key %>"><%= value %></div>
      <% end %>

_form.html.erb

    <% if @episode.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@episode.errors.count, "error") %> prohibited this episode from being saved:</h2>

          <ul>
            <% @episode.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div>
    <% end %>

If you ever can’t remember how this is done, just generate a new app and view the default rails output.

You can also extract this logic into a partial and access as follows:

<%= render 'shared/error_messages' %>

Filed under: rails Tagged: error messages, rails

Viewing all articles
Browse latest Browse all 48

Trending Articles