rails-flash

Rails flashes are just name value pair hashes

$ rails console
>> flash = { success: "It worked!", error: "It failed." }
=> {:success=>"It worked!", error: "It failed."}

To add them to your rails app go

app/views/layouts/application.html.erb

<html>
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |key, value| %>
        <div class="alert alert-<%= key %>"><%= value %></div>
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
    </div>
  
  </body>
</html>

This will produce

<div class="alert alert-success">Welcome to the Sample App!</div>

substituting the key value pair into the div. That’s why you can go flash[:error] and get a different style applied.

Then in your controller all you have to do is

controller.rb

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

end

The nice styling you see comes via Twitter Bootstrap. Go here for a how to on that:

https://agilewarrior.wordpress.com/2014/03/06/how-to-create-a-new-rails-app-with-twitter-bootstrap/

links that help
http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#sec-the_flash

Advertisements