Rails Flash messages for user feedback

Maya Patel Jan 2026
2 tabs
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
2 files · ruby, erb Explain with highlit

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.