The solution to this problem can be divided into two phases. Phase 1 fixes the ActionController::InvalidAuthenticityToken error ActionController::InvalidAuthenticityToken , and phase 2 addresses the issue of long tabs without waiting.
Phase 1 (1st variation)
One way is to redirect the user back to their location before the error. E.g. if Alice has 3 tabs open, the first expires, and Alice enters her again because she is viewing it. But when it moves to tab 3, which has the URL ' http://example.com/ex ' and submits the form. Now, instead of displaying its error, we can redirect it back to http://example.com/ex 'with its submitted form values โโthat have already been pre-filled in the form for ease of use.
This can be achieved by following this approach:
1) ApplicationController - add this function:
def handle_unverified_request flash[:error] = 'Kindly retry.'
2) You need to specify a default value for all form fields. This will be the name of this field.
... <% f.text_field, name: 'email', placeholder: 'Email', value: params[:email] %> ...
Thus, whenever Alice submits a form with the wrong authenticity_token , she will be redirected back to her form with the original values โโthat she submitted, and she will be shown a flash message that will voluntarily repeat your request.
Phase 1 (second variation)
Another way is to simply redirect Alice back to the form she submitted without any pre-populated values.
This approach can be achieved by:
1) ApplicationController - add this function:
def handle_unverified_request flash[:error] = 'Kindly retry.' redirect_to :back end
Phase 2
To solve the problem of long-awaited tabs, you can use SSE. Rails 4 has an ActionController::Live to handle SSE.
1) Add this to any controller:
include ActionController::Live ... def sse response.headers['Content-Type'] = 'text/event-stream' sse = SSE.new(response.stream, retry: 2000, event: 'refresh')
2) Provide the above function a GET route in your routes file. Lets call this route '/ sse'
3) Add this to your layout:
<% if user_signed_in? %> # check if user is signed-in or not <script> var evtSource = new EventSource("/sse"); evtSource.addEventListener('refresh', function(e){ if(e.data == 'refresh'){ window.location = window.location.href; } }); </script> <% end %>
Note: Using EventSource is not supported by all browsers. Check your browser compatibility section .
Source: rails 4 redirect back with new parameters and MDN: use events sent by server