Skip to content

Commit

Permalink
Keep flash in Turbo Frame requests (#699)
Browse files Browse the repository at this point in the history
A POST request can set the flash and return a redirect response.
If a Turbo-Frame request that gets made before the redirect location
gets called, the flash gets discared by the Turbo-Frame request.

By making sure a Turbo-Frame request keeps the flash, we can avoid this
problem.
  • Loading branch information
p8 authored Nov 7, 2024
1 parent ca2c5f4 commit 0e42702
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions app/controllers/turbo/frames/frame_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module Turbo::Frames::FrameRequest
included do
layout -> { "turbo_rails/frame" if turbo_frame_request? }
etag { :frame if turbo_frame_request? }
before_action { flash.keep if turbo_frame_request? }

helper_method :turbo_frame_request?, :turbo_frame_request_id
end
Expand Down
2 changes: 1 addition & 1 deletion test/dummy/app/controllers/messages_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def section

def create
respond_to do |format|
format.html { redirect_to message_url(id: 1) }
format.html { redirect_to message_url(id: 1), notice: "Message was successfully created." }
format.turbo_stream { render turbo_stream: turbo_stream.append(:messages, "message_1"), status: :created }
end
end
Expand Down
1 change: 1 addition & 0 deletions test/dummy/app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
</head>

<body class="<%= "turbo-native" if turbo_native_app? %>">
<%= flash[:notice] %>
<%= yield %>
</body>
</html>
16 changes: 16 additions & 0 deletions test/frames/frame_request_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ class Turbo::FrameRequestControllerTest < ActionDispatch::IntegrationTest
assert_not_equal etag_with_frame, etag_without_frame
end

test "frame requests keep the flash" do
message = Message.create!

post messages_path
assert_equal @request.flash[:notice], 'Message was successfully created.'

get messages_path, headers: { "Turbo-Frame" => "true" }
assert_equal @request.flash[:notice], 'Message was successfully created.'

get messages_path
assert_equal @request.flash[:notice], 'Message was successfully created.'

get messages_path
assert_nil @request.flash[:notice]
end

test "turbo_frame_request_id returns the Turbo-Frame header value" do
turbo_frame_request_id = "test_frame_id"

Expand Down

0 comments on commit 0e42702

Please sign in to comment.