【问题标题】:Graphql not returning associated objects in RailsGraphql没有在Rails中返回关联对象
【发布时间】:2018-04-26 00:38:14
【问题描述】:

我正在尝试返回链接到关联的 GraphQL 查询,但我得到以下信息:

在查询中,我希望演员返回所有演员(有 3 个),而不是我只是得到名字:“演员”?

任何帮助将不胜感激!

Rails 服务器日志:

我的代码如下:

app/graphql/types/movie_type.rb

Types::MovieType = GraphQL::ObjectType.define do
  name "Movie"

  field :id, !types.ID
  field :title, !types.String
  field :description, !types.String
  field :release_year, !types.Int
  field :actors do
    type Types::ActorType 
    argument :size, types.Int, default_value: 10
    resolve -> (movie, args, ctx) {
      movie.actors.limit(args[:size])
    }
  end
end

app/graphql/types/query_type.rb

field :movie, Types::MovieType do
    argument :id, !types.ID
    resolve -> (obj, args, ctx) {
      Movie.find(args[:id])
    }
end

app/models/movie.rb

class Movie < ApplicationRecord
  has_and_belongs_to_many :actors
  has_and_belongs_to_many :users
end

schema.rb

ActiveRecord::Schema.define(version: 20180424112411) do

  create_table "actors", force: :cascade do |t|
    t.string "name"
    t.string "image"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "actors_movies", id: false, force: :cascade do |t|
    t.integer "actor_id", null: false
    t.integer "movie_id", null: false
  end

  create_table "movies", force: :cascade do |t|
    t.string "title"
    t.integer "release_year"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end

【问题讨论】:

    标签: ruby-on-rails graphql


    【解决方案1】:

    我找到了答案,在 movie_type.rb 中我需要这个改变:

    类型类型[Types::ActorType]

    我猜这一定是因为设置它返回一个数组而不是返回一个实体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2019-05-28
      • 2021-12-18
      相关资源
      最近更新 更多