Rails中GraphQL无法返回关联对象问题求助
name: "Actor" Instead of Actual Movie Actors in GraphQL Hey there! Let's dig into why your GraphQL query is returning name: "Actor" instead of the real 3 actors for your movie. This usually happens when the association field isn't properly defined in your GraphQL type, or the resolution logic isn't pulling the actual associated records.
First, Fix the MovieType Definition
From your code snippet, it looks like you haven't fully defined the actors field yet. Here's how to properly set it up to fetch the associated actors:
# 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 # Fill in the type you were using here # Define the actors association correctly field :actors, !types[Types::ActorType] do resolve ->(movie, _args, _ctx) { # Make sure your Movie model has a `has_many :actors` association movie.actors } end end
Next, Ensure ActorType is Properly Defined
You need a corresponding ActorType to tell GraphQL what fields to return for each actor. If this is missing or incomplete, you'll get unexpected results:
# app/graphql/types/actor_type.rb Types::ActorType = GraphQL::ObjectType.define do name "Actor" field :id, !types.ID field :name, !types.String # Add any other fields you want to return (e.g., birthday, character_name) end
Verify Your Model Associations
Double-check that your Rails models have the correct associations set up—this is the foundation for pulling the data:
# app/models/movie.rb class Movie < ApplicationRecord has_many :actors end # app/models/actor.rb class Actor < ApplicationRecord belongs_to :movie end
Adjust Your GraphQL Query
Make sure your query is requesting the specific fields you want from the actors, not just the actors field alone (which would default to the record's to_s output, hence "Actor"):
query GetMovieWithActors { movie(id: "YOUR_MOVIE_ID") { title release_year actors { id name } } }
Why This Works
The issue you're seeing is likely because you either:
- Didn't define the
actorsfield inMovieTypeto useActorType(instead, it was defaulting to a string type, returning the class name) - Forgot to resolve the association to pull the actual
actorsrecords from the database - Had an incomplete or missing
ActorTypedefinition
Once you make these changes, your query should return the full list of actors with their actual names instead of the generic "Actor" string.
内容的提问来源于stack exchange,提问作者MLZ

