Reputation: 133
I have a controller action in Rails as follows:
def register
if logged_in?
current_user().courses << Course.find(params[:course_id])
flash.notice = 'Successfully registered!'
redirect_to '/'
else
flash.alert = "You must be logged in"
redirect_to '/courses'
end
end
This is rendered in the /courses
view as
<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>
However, when I go to a different route and then return to /courses
, the notice briefly flashes before going away. Is this normal behavior? If so, why is it occurring? If not, what am I doing wrong?
Upvotes: 1
Views: 899
Reputation: 111
Working with Rails 7.1 and ran into this issue. This is indeed due to turbo's caching:
Turbo Drive maintains a cache of recently visited pages. This cache serves two purposes: to display pages without accessing the network during restoration visits, and to improve perceived performance by showing temporary previews during application visits.
There's a quote specifically addressing this issue when using flash:
Certain page elements are inherently temporary, like flash messages or alerts. If they’re cached with the document they’ll be redisplayed when it’s restored, which is rarely desirable. You can annotate such elements with data-turbo-temporary to have Turbo Drive automatically remove them from the page before it’s cached.
The solution for individual elements is to add a data-turbo-temporary
attribute to the element to have turbo drive remove them before the page is cached.
<% if flash[:notice] %>
<div class="notice" data-turbo-temporary><%= flash[:notice] %></div>
<% end %>
Upvotes: 0
Reputation: 501
I am using "rails", "~> 7.0.6"
and I had to put the following into the <head>
tag in application.html.erb
:
<meta name="turbo-cache-control" content="no-cache">
The reason for this is because there is caching going on with Turbolinks enabled. This solution has one downside - it will remove the page caching illusion from your pages. If you can go without this, then this is the solution for you.
Upvotes: 1
Reputation: 1279
If you don't want the flash to show up again, use flash.now
instead:
flash.now[:notice] = 'Successfully registered!'
As you are doing session detection directly in your controller methods, I highly recomend you to use action filters:
before_action :logged_in, only: [:register]
# ...
def register
# ...
end
Here logged_in
should be a method to make sure user is registered and logged in. Check Filters for more information.
Upvotes: 3