0

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?

Sam S.
  • 113
  • 1
  • 7
  • search your project and see if `flash.notice` is being set anywhere else or somehow duplicated by multiple controllers. Also see https://api.rubyonrails.org/classes/ActionDispatch/Flash.html – lacostenycoder Oct 23 '18 at 01:02
  • This is most likely related to Turbolinks: "`Turbolinks will immediately restore the page from cache and display it as a preview while simultaneously loading a fresh copy from the network. This gives the illusion of instantaneous page loads for frequently accessed locations.`". You can check workarounds to the caching issue here: https://github.com/turbolinks/turbolinks/issues/309#issuecomment-360278366 – ldeld Oct 23 '18 at 14:06
  • You can also check the following question: https://stackoverflow.com/questions/42542471/rails-turbolinks-5-flash-messages – ldeld Oct 23 '18 at 14:09

2 Answers2

3

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.

Galaxy
  • 1,129
  • 11
  • 27
0

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.

Matic
  • 393
  • 3
  • 12