我正在尝试实现一种可以按记录名称而不是 id 进行搜索的查询类型。这是它在 query_type.rb
中的定义.
# Get game by name
field :game_by_name, Types::GameType, null: false do
argument :name, String, required: true
end
def game_by_name(name:)
Game.where(name: name) //find a game using the name attribute
end
但是当我运行时:
query {
gameByName(name: "League of Legends") {
id
name
}
}
我收到以下错误。
Failed to implement Game.id, tried:\n\n
- `Types::GameType#id`, which did not exist\n
- `Game::ActiveRecord_Relation#id`, which did not exist\n
- Looking up hash key `:id` or `\"id\"` on `#<Game::ActiveRecord_Relation:0x00007f5644442888>`, but it wasn't a Hash\n\n
To implement this field, define one of the methods above (and check for typos)\n
这很奇怪,因为以下查询类型可以完美运行。
# Get game by ID
field :game_by_id, Types::GameType, null: false do
argument :id, ID, required: true
end
def game_by_id(id:)
Game.find(id)
end
这是
game_type.rb
:module Types
class GameType < Types::BaseObject
field :id, ID, null: false
field :name, String, null: false
end
end
我该如何解决这个问题?谢谢!
最佳答案
我偶然发现了这一点,追逐了类似的错误。不确定你是否解决了它,但我相信问题出在查询类型定义中。
你告诉它返回类型 Types::GameType
,但 Active Record 查询返回一个 Active Record Relation,它是一个集合。因此,graphql 期待 Game
的单个实例,而是接收一个集合。然后 Graphql 尝试将查询的返回值映射到类型定义,但无法映射。最好的提示来自这一行:
Looking up hash key `:id` or `\"id\"` on `#<Game::ActiveRecord_Relation:0x00007f5644442888>`, but it wasn't a Hash..
Graphql 正在尝试分配 :id
到 ActiveRecord_Relation
它做不到。有两条前进的道路,具体取决于您希望 API 的行为方式。您希望它返回 1 条记录还是多条记录?
包装
Types::GameType
括号内将告诉 graphql 它是一个集合并遍历记录# Get game by name
field :game_by_name, [Types::GameType], null: false do
argument :name, String, required: true
end
def game_by_name(name:)
Game.where(name: name) //find a game using the name attribute
end
或者让 Active Record 只返回 1 条记录,比如......# Get game by name
field :game_by_name, Types::GameType, null: false do
argument :name, String, required: true
end
def game_by_name(name:)
Game.where(name: name).limit(1).first //find a game using the name attribute
end
我知道这已经有几个月的历史了,但是就像我一样,只是将其发布给任何偶然发现这个问题的人!
关于ruby-on-rails - Rails + Graphql - 无法实现 Game.id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61626245/