After submitting a form, you set a flash message and redirect the user. The flash message will be rendered by the _flash partial.
# pages_controller.rb
def update
if @page.update(page_params)
flash[:success] = "Page saved"
redirect_to @page
else
render :edit, status: :unprocessable_entity
end
end
Flash messages without redirects Adding a partial to your layout works fine when using redirects, but sometimes you don't want to redirect the user. A good example is sorting pages in Spina CMS. Users can drag and drop pages in any order. After dragging, a hidden form will be submitted that will save the new order. A flash message immediately appears telling the user that the sort has been saved. Without any redirects!
Step 1 Start by wrapping your flash partial with a turbo-frame.
Step 2 Instead of responding to your form submission with a redirect, respond using turbo_stream. Remember to use flash.now to set your flash message. Use render turbo_stream to render a turbo-stream-tag that updates your flash frame with a new flash partial.
Step 3 You're done. It's that simple with Hotwire.
It's a good idea to refactor the turbo_stream call into a separate method render_flash so it's easy to reuse.
# application_controller.rb
def render_flash
render turbo_stream: turbo_stream.update("flash", partial: "shared/flash")
end
Optional: confetti! In Spina CMS publishing a page is cause for celebration. That's why there's a special flash message type flash[:confetti]. When used it adds the data-controller="confetti" attribute to a flash message, resulting in a huge blast of confetti.
Feel free to steal my confetti_controller.js using canvas-confetti: