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

use*_*454 5 json ruby-on-rails

我想使用Json将一些数据从移动应用程序添加到我的rails应用程序,它运行正常,如果我使用GET方法但是当我使用POST方法设置它时它会给出错误"status":"422","error": "不可处理的实体".

路线是

resources :photomsgs, :defaults => { :format => 'json' }
Run Code Online (Sandbox Code Playgroud)

我的控制器是

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
Run Code Online (Sandbox Code Playgroud)

我正在使用这个Json网址 - http://infinite-depths-5848.herokuapp.com/photomsgs

mr *_*i.o 5

这篇文章已经有一段时间了,但今天我偶然发现了它,因为我在给json端点发帖时遇到了类似的错误.我将在这里发布解决方案以帮助其他人.

发生这种情况时日志中的错误是ActionController :: InvalidAuthenticityToken ....

为了解决这个问题,我补充道:

skip_before_action:verify_authenticity_token,if :: json_request?

在控制器的顶部,并定义了json_request方法如下:

保护

def json_request?request.format.json?
结束


Joe*_*Dyk -1

检查您的验证并确保您发布的数据符合这些验证。