Understanding Rails Flash Messages

Flash Messages in Rails thumbnail
Ahmed Abd El-Latif Ahmed Abd El-Latif
April 2024
Rails UX
Share Share

Flash messages in Rails are a simple way to give feedback to users after actions like creating, updating, or deleting records. They are easy to use and make your app feel more interactive and user-friendly.

How to Use Flash Messages

In your controller, you can set a flash message like this:

                
def create
  @post = Post.new(post_params)
  if @post.save
    flash[:notice] = "Post was successfully created!"
    redirect_to @post
  else
    flash[:alert] = "There was an error creating the post."
    render :new
  end
end
                
            

And in your layout (e.g., application.html.erb ):

                
<% flash.each do |key, message| %>
  <div class="flash <%= key %>"><%= message %></div>
<% end %>
                
            

That's it! Now your users will see helpful messages after their actions.

Related Posts

Comments

Comments coming soon!

← Back to Blog