Rails GraphQL: Query the fields of an associated entity-type via the foreign key

Viewed 223

My data-model is this way: A vendor has many cars. A car belongs to one vendor.

So I got the ID of the respective vendor in each car-entity. What I like to have are the other fields of the vendor. Like vendor-name, country etc.

I finally have accomplished the described task:

screenshot

Here is the code, which I have written.

The CarType:

module Types
    class CarType < Types::BaseObject
        field :id, ID, null: false
        field :name, String, null: false
        field :vendor_id, ID, null: false
        field :vendor, [String], null: true

        def vendor
            vendor = Vendor.find(object.vendor_id)
            [vendor[:name], vendor[:country]]
        end
    end
  end
  

And the root-type definition, plus resolver-function:

field :car, CarType, null: false,
  description: "A single car-entity." do 
    argument :id, ID, required: true
  end
def car(id:)
  Car.find(id)
end

It works, but I like to ask:

Is my implementation correct, so that it can be used that way?

Or has it to be done differently?

In case so: How has it to be done?

0 Answers
Related