Skip to content

Backend Training: Flash Message

Nelson Lee edited this page Dec 1, 2017 · 2 revisions

🔖 flash

Next we need to add flash messages to give some feedbacks to the visitors.

Let's start by adding messages for success and error state

# app/controllers/contacts_controller.rb
class ContactsController < ApplicationController

  ......

  def create
    @contact = Contact.new contact_params
    if @contact.save
      @contact = Contact.new
      flash.now[:success] = t('.success')
    else
      flash.now[:error] = @contact.errors.full_messages&.to_sentence
    end
    render 'new'
  end

  ......

end

Add a translation for the success message

en:
  ......

  contacts:
    new:
      ......
    create:
      success: Successfully Sent!

And add flashes to the view

# app/views/contacts/new.slim
section.jumbotron[id='hero']
  ......

section[id='contact-info']
  .container
    .row
      .col-md-12
        h2= t('.contact_info.title')
    .row
      .col-md-5
        p= t('.form.description')
        - if flash[:error]
          .alert.alert-danger= flash[:error]
        - elsif flash[:notice]
          .alert.alert-success= flash[:success]
        ......
      .col-md-7
        ......

Click on the submit button again now you should see the flash messages for both error and success states.

create#error create#success

Let's commit and move on...

$ git add -A
$ git commit -m 'Flash Messages'

↪️ Next Section: View Helper

Clone this wiki locally