class PostsController < ApplicationController
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = 'Post was successfully created.'
redirect_to @post
else
flash.now[:alert] = 'Failed to create post.'
render :new, status: :unprocessable_entity
end
end
def destroy
@post = current_user.posts.find(params[:id])
@post.destroy
respond_to do |format|
format.html do
flash[:notice] = 'Post was successfully deleted.'
redirect_to posts_url
end
format.json do
render json: { message: 'Post was successfully deleted.' }, status: :ok
end
end
end
end
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
</head>
<body>
<% flash.each do |type, message| %>
<div class="alert alert-<%= type %>">
<%= message %>
</div>
<% end %>
<%= yield %>
</body>
</html>
Flash messages provide one-time notifications across requests, perfect for confirming actions or showing errors. I use flash[:notice] for success messages and flash[:alert] for errors. Flash persists in session storage for one request, then auto-deletes. For AJAX requests, I return flash messages in JSON responses since redirects don't happen. The flash hash supports any keys—I add :warning and :success for semantic variety. Flash messages display in layouts, typically near the top of pages. For APIs serving React, I skip flash entirely and send messages in response bodies. Flash works beautifully for traditional request/response but needs adaptation for SPAs.