【问题标题】:JSON request not parsed into parametersJSON 请求未解析为参数
【发布时间】:2020-01-28 21:22:07
【问题描述】:

花了一个下午的谷歌搜索和测试后,我确信缺少一块 rails 魔法,但不知道它在哪里。

我有一个测试可以复制生产中出现的错误。

导轨 4.2.11.13

使用 protected_attributes gem(所以不是强参数问题)

我成功向 api 控制器发送了一个 json 请求,但它只创建了一个空版本的 payment_allocation 参数。

控制器...

class Api::V1::PaymentAllocationsController < Api::ApiController
  def create
    p request.content_type
    p request.body.read
    p params
    p self._wrapper_options
  end
end 

在控制器中看到的请求正文...

"{\"amount\":123.33,\"transaction_type\":\"Transaction\",\"claim_number\":\"ABC-123\",\"resolved\":false,\"paid_on\":\"2000-01-01\"}"

内容类型.... “应用程序/json”

生成的 params 对象...

{"controller"=>"api/v1/payment_allocations", "action"=>"create", "payment_allocation"=>{}}

我确认所有必要的属性都可用于 wrap_parameters 使用的选项

 <struct ActionController::ParamsWrapper::Options name="payment_allocation", 
format=[:json], 
include=["paid_on", "amount", "resolved", "claim_number", "transaction_type"], 
exclude=nil, klass=Api::V1::PaymentAllocationsController, 
model=PaymentAllocation(id: integer, paid_on: date, claim_number: string, transaction_type: string, amount: decimal, resolved: boolean)>

wrap_parameters 初始化器是这样的......

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
  wrap_parameters format: [:json]
end

# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
  self.include_root_in_json = false
end

我已经确认初始化器正在被调用。

所以wrap_parameters有正确的类、正确的属性等,但实际上并没有设置payment_allocation中的参数值。

我最好的猜测是有些东西无法解析 json 字符串,但是上面字符串的 JSON.parse 会返回这个......

{"amount"=>123.33, "transaction_type"=>"Transaction", "claim_number"=>"ABC-123", "resolved"=>false, "paid_on"=>"2000-01-01"}

欢迎任何提示。

(顺便说一句,我有一个应用程序在相同版本的 rails 中具有相同的代码,但没有此问题。)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    发现了问题,或者更准确地说,我的同事发现了。

    我们正在使用 Rails LTS 来支持我们的一些旧应用程序,application.rb 文件中有 LTS 的配置设置。

    我们最初将这个设置为...

    config.rails_lts_options = {
      default: :hardened
    }
    

    LTS docs 中,我们了解到此设置的影响之一是它禁止将 JSON 请求解析为参数。

    将设置更改为...

    config.rails_lts_options = {
      default: :compatible
    }
    

    启用将 JSON 请求解析为参数,这是 Rails 自然所做的。一切都按预期进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 2021-01-18
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多