Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 597
user2993454 Avatar asked Mar 12 '15 20:03

user2993454


2 Answers

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

like image 98
mr i.o Avatar answered Sep 22 '22 01:09

mr i.o


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
like image 23
bukk530 Avatar answered Sep 24 '22 01:09

bukk530