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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With