4

I'm getting ActionController::InvalidAuthenticityToken in rails 5. It was working correctly for a while, and then just gave up working.

# Application Controller
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

I'm using the rails form helper, and passing in a form object

# price_history/new.html.erb
<%= form_for @price_history_form, url: 'price_history' do |f| %>
  ...
<% end %>

I can see the authenticity token being generated in the html, and passed into the controller..

class PriceHistoriesController < ApplicationController

I'm at a loss as to why this is happening. Any thoughts?

mark
  • 833
  • 8
  • 21
  • In what situation are you getting that error ? Or are you getting it always ? – Alexander Luna Jun 12 '17 at 01:40
  • Hi @AlexanderLuna every form submission now. I've restarted the server multiple times, closed the browser, etc. – mark Jun 12 '17 at 01:43
  • @mark did you get this figured out? If so, please feel free to submit your own answer or mark the correct answer so that others that run in to this same problem can more easily find the solution. – OneNeptune Jun 12 '17 at 02:29
  • @OneNeptune, yep turbolinks + the :url option! thanks – mark Jun 12 '17 at 02:49

5 Answers5

7

An easy fix without the need of disabling Turbolinks with the Rails native UJS implementation:

$(document).on('turbolinks:load', function() {
    Rails.refreshCSRFTokens();
});
Phitherek_
  • 734
  • 1
  • 8
  • 13
3

For anyone else who might find this.. There were two problems.

Turbo links adding 'data-no-turbolink' => true and then the url: needed to start with a /

mark
  • 833
  • 8
  • 21
2

Not sure about internals of the problem, but this js fixed it for me (rails 5.1 with turbolinks enabled):

$(document).on("turbolinks:load",function() {
  $.rails.refreshCSRFTokens();  
})

It updates head csrf token so it matches form csrf token. Idea from here: https://github.com/rails/jquery-ujs/issues/456

nazar kuliyev
  • 1,215
  • 1
  • 12
  • 13
1

Try disabling Turbolinks. What version of Rails are you running?

For help disabling turbolinks, refer here: How to disable turbolinks in Rails 5?

OneNeptune
  • 883
  • 11
  • 20
  • 4
    Disabling a feature to solve a problem is hardly an answer. There needs to be a proper answer to this. – Ekkstein Jul 26 '18 at 15:15
1

The issue is with the :url option. According to this Rails issue, it will raise that error when you use it:

https://github.com/rails/rails/issues/24257

Apparently there are 2 solutions to this problem:

1) Disable Turbolinks in your form ('data-no-turbolink' => true)

2) Remove render stream: true from the controller action rendering the link or form

Alexander Luna
  • 5,261
  • 4
  • 30
  • 36