Abd El-Latif

Understanding Rails Flash Messages

April 2024 — by Ahmed Abd El-Latif

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:

1def create
2 @post = Post.new(post_params)
3 if @post.save
4 flash[:notice] = "Post was successfully created!"
5 redirect_to @post
6 else
7 flash[:alert] = "There was an error creating the post."
8 render :new
9 end
10end

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

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

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

← Back to Blog