user2993454
user2993454

Reputation: 220

Rails4 "status":"422","error":"Unprocessable Entity"

I want to add some data from the mobile app to my rails app using Json, It working fine, if I use the GET method but when I set it with POST method it give error "status":"422","error":"Unprocessable Entity".

The route is

resources :photomsgs, :defaults => { :format => 'json' }

My Controller is

def create
  @photomsg = Photomsg.new(photo_params)

 respond_to do |format|
  if @photomsg.save
    format.json { render json: @photomsg, status: :created }
    format.xml { render xml: @photomsg, status: :created }
  else
    format.json { render json: @photomsg.errors, status: :unprocessable_entity }
    format.xml { render xml: @photomsg.errors, status: :unprocessable_entity }
  end
end
end 

  def photo_params
    params.require(:photomsg).permit(:title, :physician, :patient)
  end

I am using this Json url - http://infinite-depths-5848.herokuapp.com/photomsgs

Upvotes: 9

Views: 39864

Answers (7)

Hitesh Ranaut
Hitesh Ranaut

Reputation: 747

This issue is related to csrf token. csrf token is mainly used to protect invalid form submission so that user will not able to submit form data from outside your rails application.

There are two ways to solve this issue.

Option 1: Remove csrf validation from current controller.

skip_before_action :verify_authenticity_token

Adding above code in your controller will skip csrf check in your controller. But it's not recommended as anyone will be able to submit data event from outside your rails application if you are using this option make sure you add more validation.

Option 2: Add CSRF token in your request. Another option to solve this issue is you can add csrf token on your custom form or to your ajax request.

Step:1 If you are not using any layout you can simply add csrf in your form using below code. If you are using layout make sure to check head Rails by default add csrf in head.

<%= csrf_meta_tags %>

this code will add csrf token if you are not using layout.

Step:2 In your ajax request add below code.

 $.ajax({
       type: "post", 
       beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
       url: "/form_submit/<%= @form.id %>" ,
       data: form_data, 
       success: function(data, textStatus, jqXHR){ 
          console.log("this is success");
       },
       error: function(jqXHR, textStatus, errorThrown){

       }
     });

Upvotes: 0

ArunKolhapur
ArunKolhapur

Reputation: 6925

In my case it was happening for AJAX calls from rails. I included this in my application.js document.ready function to resolve the issue.

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

Upvotes: 0

Sathwik Gangisetty
Sathwik Gangisetty

Reputation: 278

Send User auth token as header format to web service httppost.setHeader("Authorization:", token);

Upvotes: 0

Abhilash Aravind
Abhilash Aravind

Reputation: 21

Check your Photomsg model. I got the same error when I was using ActiveRecord association for a table that does not exist(may be a typo).

For example consider the following tables enter image description here

And the following model code

class User < ApplicationRecord
  has_many :posts
end

class Post < ApplicationRecord
  belongs_to :user
  belongs_to :author
end

Notice in the Post model I am referencing to a Author model but the posts table does not have author_id column. When you try to create entries using the Post model rails throws the error "422 Unprocessable Entity". Just removing the belongs_to association that does not exist should solve the problem.

Upvotes: 1

mr i.o
mr i.o

Reputation: 952

This post has been a while, but I stumbled over it today because I had similar error whilst doing a post to my json endpoint. I am going to post the solution here to help someone else in the future.

The error in the logs when this happens is ActionController::InvalidAuthenticityToken....

To resolved this, I added:

skip_before_action :verify_authenticity_token, if: :json_request?

right at the top of the controller, and defined the json_request method as follows:

protected

def json_request? request.format.json?
end

Upvotes: 6

bukk530
bukk530

Reputation: 1895

As said by @joe-van-dyk it looks like some kind of validation error.

Proceed this way, use byebug to debug the code and look for error messages on the model.

def create
  @photomsg = Photomsg.new(photo_params)

 respond_to do |format|
  if @photomsg.save
    format.json { render json: @photomsg, status: :created }
    format.xml { render xml: @photomsg, status: :created }
  else
    byebug
    # => @photomsg.errors.messages
    format.json { render json: @photomsg.errors, status: :unprocessable_entity }
    format.xml { render xml: @photomsg.errors, status: :unprocessable_entity }
  end
end
end 

  def photo_params
    params.require(:photomsg).permit(:title, :physician, :patient)
  end

Upvotes: 4

Joe Van Dyk
Joe Van Dyk

Reputation: 6950

Check your validations and make sure that the data you are posting meets those validations.

Upvotes: -1

Related Questions