Ruby-on-rails Rails4“状态”:“422”,“错误”:“不可处理的实体”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29019159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:07:36  来源:igfitidea点击:

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

ruby-on-railsjson

提问by user2993454

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".

我想使用 Json 将移动应用程序中的一些数据添加到我的 Rails 应用程序,它工作正常,如果我使用 GET 方法,但是当我使用 POST 方法设置它时,它会给出错误“状态”:“422”,“错误”: “不可处理的实体”。

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

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

回答by mr i.o

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.

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

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

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

To resolved this, I added:

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

skip_before_action :verify_authenticity_token, if: :json_request?

skip_before_action :verify_authenticity_token, 如果: :json_request?

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

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

protected

def json_request? request.format.json?
end

受保护

定义 json_request 吗?request.format.json?
结尾

回答by bukk530

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

正如@joe-van-dyk 所说,它看起来像是某种验证错误。

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

以这种方式继续,使用 byebug 调试代码并查找模型上的错误消息。

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

回答by Joe Van Dyk

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

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

回答by Abhilash Aravind

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).

检查您的 Photomsg 模型。当我对不存在的表使用 ActiveRecord 关联时,我遇到了同样的错误(可能是拼写错误)。

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.

请注意,在 Post 模型中,我引用了 Author 模型,但 posts 表没有 author_id 列。当您尝试使用 Post 模型创建条目时,rails 会引发错误“422 Unprocessable Entity”。只需删除不存在的belongs_to 关联即可解决问题。

回答by Sathwik Gangisetty

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

将用户身份验证令牌作为标头格式发送到 Web 服务 httppost.setHeader("Authorization:", token);

回答by ArunKolhapur

In my case it was happening for AJAX calls from rails. I included this in my application.jsdocument.readyfunction to resolve the issue.

在我的情况下,它发生在 Rails 的 AJAX 调用中。我将其包含在我的application.jsdocument.ready函数中以解决该问题。

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

回答by Hitesh Ranaut

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.

此问题与 csrf 令牌有关。csrf 令牌主要用于保护无效的表单提交,以便用户无法从 Rails 应用程序外部提交表单数据。

There are two ways to solve this issue.

有两种方法可以解决这个问题。

Option 1: Remove csrf validation from current controller.

选项 1:从当前控制器中删除 csrf 验证。

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.

在控制器中添加上述代码将跳过控制器中的 csrf 检查。但不建议这样做,因为如果您使用此选项,任何人都可以从 Rails 应用程序外部提交数据事件,请确保添加更多验证。

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.

选项 2:在您的请求中添加 CSRF 令牌。解决此问题的另一个选择是您可以在自定义表单或 ajax 请求中添加 csrf 令牌。

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.

步骤:1 如果您不使用任何布局,您只需使用以下代码在表单中添加 csrf。如果您使用布局,请确保检查 head Rails 默认情况下在 head 中添加 csrf。

<%= csrf_meta_tags %>

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

如果您不使用布局,此代码将添加 csrf 令牌。

Step:2 In your ajax request add below code.

步骤:2 在您的 ajax 请求中添加以下代码。

 $.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){

       }
     });