Engineering

Exploring Flash Messages with Turbo Streams in Rails 7

Exploring Flash Messages with Turbo Streams in Rails 7

User experience is a critical aspect of any web application, and providing timely feedback to users is crucial for a smooth and engaging user journey. Flash messages are a common way to communicate important information or alerts to users. In Rails 7, the introduction of Turbo Streams takes the user experience to a new level by enabling seamless real-time updates without the need for full-page reloads. In this blog post, we will explore how to leverage Turbo Streams in Rails 7 to enhance flash message functionality.

What are Flash Messages?

Flash messages are short-lived messages that provide feedback or notifications to users. They are typically used to display success messages, error alerts, or other informative notices. In Rails, flash messages are stored in the session and are accessible across multiple requests. By default, flash messages are displayed on the subsequent page after a form submission or action.

There are three common methods to set flash messages inside rails controller

  1. Passing as an argument to the redirect_to method.
def update
  redirect_to sample_url(@submission), notice: "Submission has been updated!"
end
  1. We can only set notice and alert keys for flash messages in the above snippet. But, if we want to set a flash message with a flash key other than notice and alert, we need to set it in a different line. Here’s how we do it:
def update
  flash[:success] = "Submission has been updated!"
  redirect_to sample_url(@submission)
end
  1. The above two methods are used when there is a page redirect. But, if we don’t want to redirect the page instead render a partial. In this case, we can use flash.now for setting the flash message.

    The flash.now object is a variant of the flash object used specifically for displaying flash messages on the current page. Unlike the regular flash object, which persists messages for the next request, flash.now is designed for immediate rendering and is cleared automatically after the current request is complete.‍

    By using flash.now, you can display flash messages without the need for an additional request or redirect. This is particularly useful when rendering a template within the same action, such as in a failed form submission or error handling scenario, where you want to show an immediate message to the user on the same page.

def create
  if success
    flash[:success] = "Form submitted successfully!"
    redirect_to success_path
  else
    flash.now[:error] = "Oops! Something went wrong."
    render :new
  end
end

There is another rare scenario where we want to retain flash messages for the next request, ensuring that they are not cleared and can be accessed and displayed on subsequent pages. In such case, we can use flash.keep to retain the flash messages.

# Controller action handling an update request for a form submission
def update
  @submission = Submission.find(params[:id])

  if @submission.update(submission_params)
    flash[:success] = "Submission updated successfully!"
    redirect_to submissions_path
  else
    flash.keep[:error] = "Error updating submission."
    redirect_to edit_submission_path(@submission)
  end
end

# Controller action for the submissions index page
def index
  @submissions = Submission.all
end

In the above example, the update action is responsible for handling the update request for a form submission. If the update is successful, the flash[:success] message is set, and the user is redirected to the submissions index page (submissions_path). On the other hand, if there is an error during the update, the flash.keep[:error] line is used to retain the :error flash message for the next request, ensuring it is not cleared.

Introducing Turbo Streams

Turbo Streams, introduced in Rails 7, is a powerful addition to Rails’ Turbo family. Turbo Streams enables developers to perform real-time updates to specific parts of a web page without reloading the entire page. This feature is achieved through the use of streams, which are small fragments of HTML or JavaScript that represent changes to be applied to the page.

Handling Flash Messages with Turbo Streams

To handle flash messages with Turbo Streams, we need to update our controller actions and views. Let’s consider an example of a user registration form.

  1. Controller Action: When a user submits the submission form, instead of rendering a full HTML response, we can utilize Turbo Streams to send a partial HTML response containing the flash message.
def update
  # Submission logic here
  # ...
  if submission.save
    flash.now[:success] = "Submission has been updated!"
  else
    flash.now[:error] = "Failed to update submission."
  end

  render turbo_stream: [
               turbo_stream.replace(
                 "turbo_id",
                 partial: "../..",
                 locals: {
                   # ...
                 },
               ),
               turbo_stream.replace("flash-messages", partial: "application/flash"),
             ]
  end
  1. View: Create a partial view to render the flash messages. This partial can be placed anywhere in your application’s views, for example, in the application folder.
<!-- app/views/application/_flash_message.html.erb -->
<div id="flash-messages">
  <% flash.each do |type, message| %>
    <div class="alert alert-<%= type %>">
      <%= message %>
    </div>
  <% end %>
</div>
  1. Rendering flash partial in your layout: In your layout or specific views where you want to handle Turbo Streams, render the flash partial.
<!-- app/views/application/_flash_message.html.erb -->
<div id="flash-messages">
  <% flash.each do |type, message| %>
    <div class="alert alert-<%= type %>">
      <%= message %>
    </div>
  <% end %>
</div>

Conclusion

Flash messages in Rails 7 are a valuable tool for providing feedback and notifications to users. With the introduction of Turbo Streams, real-time updates and seamless user experiences are now possible without full-page reloads. By combining flash messages with Turbo Streams, developers can enhance the user experience by dynamically updating flash message areas on the page. The flash.keep method allows for the persistence of flash messages across multiple requests, ensuring relevant information is displayed to users. With these features, Rails 7 empowers developers to create more interactive and responsive web applications, delivering timely and meaningful messages to users throughout their journeys.

Need help building your product?

Reach out to us by filling out the form on our contact page. If you need an NDA, just let us know, and we’ll gladly provide one!

Top software development company Malaysia awards
Loading...