ruby 在GraphQL中将自定义字段添加到类型类而不是对应的模型类

w1jd8yoj  于 2023-04-20  发布在  Ruby
关注(0)|答案(1)|浏览(131)
module Types
  class PaymentType < Types::BaseObject
    field :id, Integer, null: false
    field :amount, Integer, null: false
    field :currency, String, null: false
    field :xyz, Integer, null: true
  end
end
class Payment < ActiveRecord::Base
    field :id, Integer, null: false
    field :amount, Integer, null: false
    field :currency, String, null: false
end
module Mutations
  class CreatePayment < BaseMutation

    type Types::PaymentType
    description "Create Payment"

    argument :amount, Integer, required: true
    argument :currency, String, required: true

    def resolve(amount: , currency: )
      payment = Payment.new(amount: amount, currency: currency)
      xyz = SomeXYZ()
      payment.save
      payment
    end
  end
end

在这里,我在PaymentType中有一个额外的字段,与相应的模型相比。在我的突变的解析器中,我想获取xyz的数据,并返回一个PaymentType,其中除了payment之外还包含此xyz。
我试过只把xyz附加到payment变量上,但每次我都会得到一些或其他的错误。我也试过为PaymentType创建一个构造函数,但它也会给出错误。

module Types
  class PaymentType < Types::BaseObject
    field :id, Integer, null: false
    field :amount, Integer, null: false
    field :currency, Integer, null: false
    field :xyz, Integer, null: true

    def initialize(payment, xyz)
      self.id = payment.id
      self.amount = payment.amount
      self.currency = payment.currency
      self.xyz = xyz
    end
  end
end

我是GraphQL和Rails的新手。如果有人能在这里提出建议,那将非常有帮助。谢谢。

tzdcorbm

tzdcorbm1#

我可能没有正确地理解你的想法,因为我不确定Xyz代表什么,但我怀疑你可以用其他方式实现这个结构:

module Mutations
  class CreatePayment < BaseMutation

    type Types::PaymentType
    description "Create Payment"

    argument :amount, Integer, required: true
    argument :currency, String, required: true

    def resolve(amount: , currency: )
      payment = Payment.new(amount: amount, currency: currency)
      xyz = SomeXYZ()
      payment.save

      {
        payment: payment, # or just `payment:` in new hash format
        xyz: xyz          # or just `xyz:` in new hash format
      }
    end
  end
end

相关问题