Skip to content

Commit 0e42702

Browse files
authored
Keep flash in Turbo Frame requests (#699)
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.
1 parent ca2c5f4 commit 0e42702

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

app/controllers/turbo/frames/frame_request.rb

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ module Turbo::Frames::FrameRequest
2323
included do
2424
layout -> { "turbo_rails/frame" if turbo_frame_request? }
2525
etag { :frame if turbo_frame_request? }
26+
before_action { flash.keep if turbo_frame_request? }
2627

2728
helper_method :turbo_frame_request?, :turbo_frame_request_id
2829
end

test/dummy/app/controllers/messages_controller.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def section
1616

1717
def create
1818
respond_to do |format|
19-
format.html { redirect_to message_url(id: 1) }
19+
format.html { redirect_to message_url(id: 1), notice: "Message was successfully created." }
2020
format.turbo_stream { render turbo_stream: turbo_stream.append(:messages, "message_1"), status: :created }
2121
end
2222
end

test/dummy/app/views/layouts/application.html.erb

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
</head>
1111

1212
<body class="<%= "turbo-native" if turbo_native_app? %>">
13+
<%= flash[:notice] %>
1314
<%= yield %>
1415
</body>
1516
</html>

test/frames/frame_request_controller_test.rb

+16
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,22 @@ class Turbo::FrameRequestControllerTest < ActionDispatch::IntegrationTest
3535
assert_not_equal etag_with_frame, etag_without_frame
3636
end
3737

38+
test "frame requests keep the flash" do
39+
message = Message.create!
40+
41+
post messages_path
42+
assert_equal @request.flash[:notice], 'Message was successfully created.'
43+
44+
get messages_path, headers: { "Turbo-Frame" => "true" }
45+
assert_equal @request.flash[:notice], 'Message was successfully created.'
46+
47+
get messages_path
48+
assert_equal @request.flash[:notice], 'Message was successfully created.'
49+
50+
get messages_path
51+
assert_nil @request.flash[:notice]
52+
end
53+
3854
test "turbo_frame_request_id returns the Turbo-Frame header value" do
3955
turbo_frame_request_id = "test_frame_id"
4056

0 commit comments

Comments
 (0)