0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RailsでGraphQLを使ってみた

Last updated at Posted at 2025-09-28

はじめに

Spring BootでGraphQLを使ってみて、基礎がある程度わかってきた気がする。
そこで、以前かじったことのあるRailsでもいじってみました。

こちらの記事の基礎講座をなぞってみる。

Query

基本、コマンド一発でmodelと合わせて全部作ってくれるので便利すぎる。

types/query_type.rb が リクエスト情報とのマッピングカナ?
レスポンスの情報は、types/xxxx_type.rbに書いておく。

って感じかな。

query_type.rbにゴリゴリ書くと、query_type.rb が肥大化してしまうので、resolver を別ファイルで作ってそちらに返却ロジックを記載。

って感じかな。

resolver内でmodelを返却すると、自動でtypesとマッピングしてレスポンスを返してくれる。

もう少し深堀

modelに紐づかない場合は?

Geminiに色々聞きながら、こんな感じでも動く。

ハッシュ と レスポンスのtypeのマッピングは自動でやってくれる感じ!

query_type.rb

    field :training, Types::TrainingType, null: false do
      argument :id, ID, required: true, description: "ID of the training."
    end
    def training(id:)
      training_map = {
        "1" => "run",
        "2" => "bike",
        "3" => "swim"
      }
      name = training_map[id] || "unknown"
      { id: id, name: name }
    end

TrainingType

# frozen_string_literal: true

module Types
  class TrainingType < Types::BaseObject
    field :id, ID, null: false
    field :name, String, null: false
  end
end

リクエスト情報

{
  training(id: "1") {
    id
    name
  }
}

複数返したい場合は?
以下のように書いてあげればOK.

      training_map.map do |id, name|
        { id: id, name: name }
      end

でも良い。

      [
        { id: "1", name: "run" },
        { id: "2", name: "bike" },
        { id: "3", name: "swim" }
      ]

Mutation

基本的にはQueryと変わらず、リクエストの窓口は、mutation_type.rb になる。
但し、resolverではなく、mutationsのフォルダ配下に記載。

って感じかな。

補足資料

サンプルソース

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?