我正在尝试使用graphql-ruby
实现联合类型。
我遵循了official documentation,但遇到了下面列出的错误。
这是我当前的代码。
module Types
class AudioClipType < Types::BaseObject
field :id, Int, null: false
field :duration, Int, null: false
end
end
module Types
class MovieClipType < Types::BaseObject
field :id, Int, null: false
field :previewURL, String, null: false
field :resolution, Int, null: false
end
end
module Types
class MediaItemType < Types::BaseUnion
possible_types Types::AudioClipType, Types::MovieClipType
def self.resolve_type(object, context)
if object.is_a?(AudioClip)
Types::AudioClipType
else
Types::MovieClipType
end
end
end
end
module Types
class PostType < Types::BaseObject
description 'Post'
field :id, Int, null: false
field :media_item, Types::MediaItemType, null: true
end
end
这是graphql查询。
{
posts {
id
mediaItem {
__typename
... on AudioClip {
id
duration
}
... on MovieClip {
id
previewURL
resolution
}
}
}
}
当我发送查询时,出现以下错误。
Failed to implement Post.mediaItem, tried:
- `Types::PostType#media_item`, which did not exist
- `Post#media_item`, which did not exist
- Looking up hash key `:media_item` or `"media_item"` on `#<Post:0x007fb385769428>`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos
找不到任何错字或其他内容。
我错过了什么吗?
答案 0 :(得分:1)
您没有定义父类型(联合的超类)。
因此添加
class Types::BaseUnion < GraphQL::Schema::Union
end
现在您的继承链将保持一致。