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

Rails GraphQL中如何扩展并覆盖同模块类的参数属性?

在Rails GraphQL中覆盖InputObject的参数属性

在GraphQL-Ruby中,直接继承InputObject后重新声明参数不会自动覆盖父类的定义——父类的参数会被保留,子类新增的同名参数会导致重复注册,因此你的代码无法生效。要实现覆盖,需要使用argument方法的override: true选项,明确告知GraphQL替换父类的参数定义。

修正后的代码

创建用InputType

module Types
  module Input
    class CreateProductInputType < ProductInputType
      argument :name,           String, required: true, override: true
      argument :initial_price,  Float, required: true, override: true
    end
  end
end

更新用InputType

module Types
  module Input
    class UpdateProductInputType < ProductInputType
      argument :name,           String, required: true, override: true
    end
  end
end

原理说明

override: true是GraphQL-Ruby专门提供的用于覆盖父类字段/参数的选项,使用它后,子类的参数定义会完全替换父类中同名的参数。这样:

  • CreateProductInputType中name和initial_price变为必填,description继承父类的可选设置
  • UpdateProductInputType仅将name设为必填,其余参数保持父类的可选状态

内容的提问来源于stack exchange,提问作者Roger Peixoto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:41:01