You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在graphql-ruby突变查询中传递Boolean参数遇强制转换错误

问题原因

你遇到的错误是因为Rails测试中默认以表单数据(form data)格式发送请求时,会把Ruby的布尔值true转换成字符串"true",而GraphQL-Ruby的原生Boolean类型解析器只能识别原生布尔值,无法将字符串"true"转换为布尔类型。而Apollo Studio是直接发送JSON格式请求,布尔值保持原生类型,所以可以正常解析。

解决方法

方法1:发送JSON格式请求

在测试中,将请求设置为JSON格式,这样布尔值会保留原生类型传递给GraphQL接口:

it "works" do
  post "/graphql", 
       params: { 
         query: destroy_query, 
         variables: { "input" => { "confirm" => true } } 
       }.to_json,
       headers: { 'Content-Type': 'application/json' }
end

这种方法是最规范的,符合GraphQL接口的标准请求格式。

方法2:自定义布尔类型支持字符串转换

如果需要兼容表单数据格式的请求,可以自定义一个支持字符串转布尔的参数类型,替换原生的GraphQL::Types::Boolean:

# 定义自定义布尔类型
class Types::BooleanWithStringCoercion < GraphQL::Types::Boolean
  def self.coerce_input(value, ctx)
    if value.is_a?(String)
      value.strip.downcase == "true"
    else
      super
    end
  end
end

# 在突变中使用自定义类型
class Mutations::User::Destroy < Mutations::BaseMutation
  argument :confirm, Types::BooleanWithStringCoercion, required: true
  payload_type GraphQL::Types::Boolean

  def resolve(confirm:)
    true
  end
end

这样无论是传入原生布尔值还是字符串"true"/"false",都能正确解析。

内容的提问来源于stack exchange,提问作者John Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:47:22