0
0
Ruby on Railsframework~5 mins

Flash messages in Ruby on Rails

Choose your learning style9 modes available
Introduction

Flash messages show short, temporary messages to users after actions like saving or deleting. They help users know what happened.

After a user submits a form to confirm success or show errors.
When redirecting to another page and you want to show a message.
To notify users about login success or failure.
To alert users about permission issues or missing data.
Syntax
Ruby on Rails
flash[:notice] = "Your message here"
flash[:alert] = "Warning or error message"
redirect_to some_path

Use flash[:notice] for normal messages and flash[:alert] for warnings or errors.

Flash messages last only for the next request, usually after a redirect.

Examples
Shows a success message after updating a profile and redirects to the profile page.
Ruby on Rails
flash[:notice] = "Profile updated successfully"
redirect_to profile_path
Shows an alert message if the user is not logged in and redirects to the login page.
Ruby on Rails
flash[:alert] = "You must log in first"
redirect_to login_path
Sets a flash message without redirecting immediately. It will show on the next page load.
Ruby on Rails
flash[:notice] = "Item added to cart"
Sample Program

This controller action tries to save a new item. If it works, it sets a success flash message and redirects to the item's page. If it fails, it sets an error flash message and shows the form again.

Ruby on Rails
class ItemsController < ApplicationController
  def create
    @item = Item.new(item_params)
    if @item.save
      flash[:notice] = "Item was successfully created."
      redirect_to @item
    else
      flash.now[:alert] = "Failed to create item."
      render :new
    end
  end

  private

  def item_params
    params.require(:item).permit(:name, :price)
  end
end
OutputSuccess
Important Notes

Flash messages are stored in the session and cleared after being shown once.

Use flash.now if you want the message to appear on the current page without redirecting.

Summary

Flash messages give quick feedback to users after actions.

They last only for the next page load, usually after redirects.

Use flash[:notice] for normal info and flash[:alert] for warnings or errors.