Rails: POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller? Rails: POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller? ajax ajax

Rails: POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller?


I got it working!

I added a...

skip_before_action :verify_authenticity_token

to the controller.

The issue was found when checking out the logs and seeing that the CSRF token could not be verified.


ihaztehcodez(who was last active in 2016 so it won't help nudging him to post an answer) mentions that the skip_before_action :verify_authenticity_token technique is not so secure 'cos you lose forgery protection.

they mention that the best/secure/'better practise', solutions are mentioned here WARNING: Can't verify CSRF token authenticity rails

e.g.

$.ajaxSetup({  headers: {    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')  }});

or

$.ajax({ url: 'YOUR URL HERE',  type: 'POST',  beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},  data: 'someData=' + someData,  success: function(response) {    $('#someDiv').html(response);  }});

or

putting this within an ajax request

headers: {  'X-Transaction': 'POST Example',  'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')},


Same problem I faced.It sorts out after adding

skip_before_action :verify_authenticity_token

at the top of your controller where your JS is calling or sending data.

class UserController < ApplicationController    skip_before_action :verify_authenticity_token    def create    endend

as shown in code snippet.