TIL: Pass a Hash to Flash
Today I learned:
You are free to pass a HASH to a flash message. Not just a string 😀
# app/controllers/posts_controller.rb
flash[:post_status] = "Success. Post created" # a string
flash[:post_status] = { title: "Success", subtitle: "Post created" } # a hash!
# app/views/shared/_flash.html.erb
<% flash.each do |type, message| %>
<%= type %>
<%= message[:title] %>
<%= message[:subtitle] %>
<% end %>
You can also register new flash types with add_flash_types
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
add_flash_types :toast
This lets you use
-redirect_to root_path, flash: { toast: "success" }
+redirect_to root_path, toast: "success"
- More about ActionDispatch::Flash (official docs)
- Dismissable Flash Messages with Hotwire without page refresh
Did you like this article? Did it save you some time?