Rails has two default message display formats when you create a default application with scaffolding: notices and error messages.

notices

Notices are nice little green messages that tell you things are alright.

rails-notices

They work because rails adds a nice little notice id at the top of your show page.

marks/show.html.erb

<p id="notice"><%= notice %></p>

with some default styling:

scaffold.css.scss

#notice {
  color: green;
}

And you can trigger it in your controller by doing something like this:

marks_controller.rb

class MarksController < ApplicationController

  def show
    render action: 'show', notice: 'Sample notice'
  end

Error Messages

rails-error-messages

Error messages are for when things go wrong. They are set on the model, and then displayed on the page.

At the top of any scaffolding generated rails form you will see:

marks/_forms.html.erb

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

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

This is basically rails saying:”If there are any errors, I am going to display them”. This might happen if a save fails like below.

marks_controller.rb

  def create
    @mark = Mark.new(mark_params)

    respond_to do |format|
      if @mark.save
        format.html { redirect_to @mark, notice: 'Mark was successfully created.' }
        format.json { render action: 'show', status: :created, location: @mark }
      else
        format.html { render action: 'new' }
        format.json { render json: @mark.errors, status: :unprocessable_entity }
      end
    end
  end

Here is the corresponding styling for the errors.

scaffold.css.scss

scaffold.css.scss
.field_with_errors {
  padding: 2px;
  background-color: red;
  display: table;
}

#error_explanation {
  width: 450px;
  border: 2px solid red;
  padding: 7px;
  padding-bottom: 0;
  margin-bottom: 20px;
  background-color: #f0f0f0;
  h2 {
    text-align: left;
    font-weight: bold;
    padding: 5px 5px 5px 15px;
    font-size: 12px;
    margin: -7px;
    margin-bottom: 0px;
    background-color: #c00;
    color: #fff;
  }
  ul li {
    font-size: 12px;
    list-style: square;
  }
}
Advertisements