ruby-on-railsajaxdeviseauthenticity-token

Rails 4 Login/Sign up using devise during form submission authenticity token error


I have a Project model. There's one-to-many association with the Project model and the Devise User model. I want the users to perform ajax login using Devise before submitting the Projects form data.

The Ajax login works fine. But, after the login when I try and submit the Projects form I get an authenticity token error. I understand that this is due to the change of session token change. But I wonder if there's any way to maintain this kind of user flow?


Solution

  • I think I fixed it with some simple jQuery code. I basically needed to replace the existing authenticity token on the parent form with the new one after sign in. Previously had enabled the Devise session method to respond to js format and had the file /devise/sessions/create.js.erb.

    On the same file I had to append the following jQuery code to replace the existing authenticity token on the form with the new one generated after logging in.

    $("input[name='authenticity_token'").val("<%= form_authenticity_token %>");