ruby-on-rails - 如何使用 graphql-ruby 指定多态类型?

标签 ruby-on-rails ruby graphql

我有一个 UserType 和一个可以是 Writer 或 Account 的 userable。

对于 GraphQL,我想也许我可以像这样使用 UserableUnion:

UserableUnion = GraphQL::UnionType.define do
  name "Userable"
  description "Account or Writer object"
  possible_types [WriterType, AccountType]
end

然后像这样定义我的用户类型:

UserType = GraphQL::ObjectType.define do
  name "User"
  description "A user object"
  field :id, !types.ID
  field :userable, UserableUnion
end

但我得到 schema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' 函数

我试过在多个地方放置一个 resolve_type,但我似乎无法弄明白?

现在有人知道如何实现吗?

最佳答案

该错误意味着您需要在应用架构中定义 resolve_type 方法。它应该接受一个 ActiveRecord 模型和上下文,并返回一个 GraphQL 类型。

AppSchema = GraphQL::Schema.define do
  resolve_type ->(record, ctx) do
    # figure out the GraphQL type from the record (activerecord)
  end
end

您可以实现 this example它将模型链接到类型。或者您可以在您的模型上创建一个类方法或属性来引用它们的类型。例如

class ApplicationRecord < ActiveRecord::Base
  class << self
    attr_accessor :graph_ql_type
  end
end

class Writer < ApplicationRecord
  self.graph_ql_type = WriterType
end

AppSchema = GraphQL::Schema.define do
  resolve_type ->(record, ctx) { record.class.graph_ql_type }
end

关于ruby-on-rails - 如何使用 graphql-ruby 指定多态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40541391/

相关文章:

ruby-on-rails - Rails 4.2.6 + 多态 + Carrierwave 0.10 + 条件

ruby-on-rails - Rails 4 + nginx + unicorn + ssl = 502 错误网关

ruby-on-rails - Rails : import timestamps, 不同时区和夏令时

ruby - 在reduce block 中使用选择

ruby 扩展任务 : How to make it dependent of another rake task?

graphql - GraphQL 中的查看器字段是什么意思?

ruby-on-rails - 将 JSON 数据导入 Rails

ruby - 如何在事务中发生 DataMapper 回调?

graphql - 抑制 GraphQL : Syntax Error in VS Code when using template string

java - 在 Java 应用程序中禁用 GraphQL 自省(introspection)日志记录