【问题标题】:Rails4 "status":"422","error":"Unprocessable Entity"Rails4“状态”:“422”,“错误”:“无法处理的实体”
【发布时间】:2015-03-12 20:02:11
【问题描述】:

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

路线是

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

我的控制器是

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

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

【问题讨论】:

  • 只是表示无法保存新模型。在保存之前尝试检查模型是否有效,并且所有 photo_params 都存在。
  • 你检查了我的 Json url,创建方法是否正确? infinite-depths-5848.herokuapp.com/photomsgs

标签: ruby-on-rails json


【解决方案1】:

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

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

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

skip_before_action :verify_authenticity_token, if: :json_request?

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

受保护

def json_request? request.format.json?
结束

【讨论】:

    【解决方案2】:

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

    按此操作,使用 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
    

    【讨论】:

    • 它工作正常我从rails网页(表单)提交数据,但是当我使用post方法通过infinite-depths-5848.herokuapp.com/photomsgs上的Json从Iphon发送数据时它给出了错误。
    • 您的 JSON 格式不正确。也许您没有使用正确的键名。
    【解决方案3】:

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

    例如考虑以下表格

    以及以下型号代码

    class User < ApplicationRecord
      has_many :posts
    end
    
    class Post < ApplicationRecord
      belongs_to :user
      belongs_to :author
    end
    

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        在我的例子中,它发生在来自 rails 的 AJAX 调用中。我将此包含在我的 application.js document.ready 函数中以解决此问题。

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

        【讨论】:

          【解决方案6】:

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

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

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

          skip_before_action :verify_authenticity_token
          

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

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

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

          <%= csrf_meta_tags %>
          

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

          步骤: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){
          
                 }
               });
          

          【讨论】:

            【解决方案7】:

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

            【讨论】:

            • 我从未在我的模型中使用任何类型的验证我的模型看起来像:class Photomsg
            猜你喜欢
            • 1970-01-01
            • 2014-12-24
            • 2018-03-01
            • 1970-01-01
            • 2023-03-22
            • 2018-12-31
            • 1970-01-01
            • 2022-10-15
            • 1970-01-01
            相关资源
            最近更新 更多