graphql-rubyでmethodオプションを使って、modelに定義したメソッドをfieldにする方法

こんにちは!kossyです!




さて、今回はgraphql-rubyでmethodオプションを使ってmodelに定義したメソッドをfieldにする方法について、ブログに残してみたいと思います。



環境

Ruby 2.6.3
Rails 6.0.3.4
graphql 1.11.6



方法

Userモデルがあるとして、以下のメソッドを定義します。

class User < ApplicationRecord

  def full_name
    last_name + first_name
  end
end

app/graphql/types/user_type.rbは以下のような定義にします。

module Types
  class UserType < Types::BaseObject
    implements Types::TimestampInterface

    field :id, ID, null: false
    field :full_name, String, null: true, method: :full_name
    field :email, String, null: true

methodオプションにUserモデルに定義したfull_nameを渡すことで、そのままfieldとすることができます。




勉強になりました。