Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Fix Rails Flash Rendering When Using Hotwire

I added Hotwire to a Ruby on Rails application I’ve been working on and discovered some issues when rendering flash messages. Yesterday I wrote about problems related to CORS error using OmniAuth.  Today’s is not as exciting but still as annoying.

Problem

I was in the process of testing some validation changes I implemented and realized errors were not being displayed. I went through the typical debug scenarios and found that errors were being returned but just not displayed.

The code consists of just trying to create a user:

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to root_path, notice: “User created successfully“
  else
    render :new
  end
end

When creating a user, the new form rendered but errors were not displayed.

Solution

The reason the messages were not being displayed is because of Turbo and Rails UJS conflicting. Solving the problem can be done in one of two ways.

1. It appears Turbo expects form submissions to redirect to a new location. When there is an error, we are staying on the same page. Adding status: :unprocessable_entity to the render fixes the problem.

def create
  @user = User.new(user_params)
  if @user.save
    redirect_to root_path, notice: “User created successfully“
  else
    render :new, status: :unprocessable_entity 
  end
end

2. A similar solution from yesterday’s post also works. Adding

data: { turbo: false }

The form declaration disables turbo and lets Rails UJS handle as desired.

I hope future versions of Turbo handle this better.

The post How to Fix Rails Flash Rendering When Using Hotwire appeared first on Accidental Technologist.



This post first appeared on Accidental Technologist - Musings About Entreprene, please read the originial post: here

Share the post

How to Fix Rails Flash Rendering When Using Hotwire

×

Subscribe to Accidental Technologist - Musings About Entreprene

Get updates delivered right to your inbox!

Thank you for your subscription

×