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
相关产品推荐
相关产品推荐

