9
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのGraphQLで`Field xxx doesn't exist on type ???` と怒られたら

Last updated at Posted at 2019-06-13

TL;DR

{
  house(id: 1) {
    id,
    name,
    # city_name, # Bad!
    cityName, # Good!
  }
}

現象

Railsでgraphqlを使うとき、下記のタイプを定義しました。

house_type.rb
module Types
  class HouseType < Types::BaseObject
    field :id, ID, null: false
    field :name, String, null: false
    field :city_name, String, null: false
  end
end

そしてquery_type.rbにも追記しました

query_type.rb
module Types
  class QueryType < Types::BaseObject
    field :house, Types::HouseType, null: true do
      description "Find a house by ID"
      argument :id, ID, required: true
    end
    def house(id:)
      House.find(id)
    end
  end
end

query投げてみると

{
  house(id: 1) {
    id,
    name,
  }
}

戻った結果は

{
  "data": {
    "house": {
      "id": "1",
      "name": "Taro",
    }
  }
}

しかしcity_nameに対してもQueryしたら

{
  house(id: 1) {
    id,
    name,
    city_name,
  }
}

こんなエラーが返されました。

{
  "errors": [
    {
      "message": "Field 'city_name' doesn't exist on type 'House'",
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "path": [
        "query",
        "house",
        "city_name"
      ],
      "extensions": {
        "code": "undefinedField",
        "typeName": "House",
        "fieldName": "city_name"
      }
    }
  ]
}

解決

公式Docを読んでみると

class Types::PostType < Types::BaseObject
  ...
  field :truncated_preview, String, null: false
  ...
end
query_string = "
{
  post(id: 1) {
    id
    title
    truncatedPreview
  }
}"

と記載していて、なるほど、Queryのフィールドはカーメル式じゃなければいけないですね。

早速試してみると

{
  house(id: 1) {
    id,
    name,
    cityName,
  }
}
{
  "data": {
    "house": {
      "id": "1",
      "name": "Taro",
      "cityName": "Tokyo",
    }
  }
}

無事、成功しました。

9
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?