Rails / GraphQL中的AssociationTypeMismatch?

时间:2018-06-20 14:45:28

标签: ruby-on-rails graphql

所以我的数据非常简单。书籍和用户。

class Books
 belongs_to :user
end

class Users
 has_many :books
end

用户具有以下字段:

first_name
last_name
email

书籍具有以下字段:

author
title
description

我的book_type看起来像:

Types::BookType = GraphQL::ObjectType.define do
 name 'Book'
field :id, !types.ID
field :author, !types.String
field :title, !types.String
field :user, -> {Types::UserType}, property: :user
end

User_type如下:

Types::UserType = GraphQL::ObjectType.define do
 name 'User'
 field :id, !types.ID
 field :first_name, !types.String
 field :last_name, !types.String
 field :email, !types.String
end

Mutation_type如下:

Types::MutationType = GraphQL::ObjectType.define do
 name 'Mutation'
 field :bookCreate, function: Resolvers::BookCreate.new
end

Book_create文件如下:

class Resolvers::BookCreate < GraphQL::Function
 argument :author, !types.String
 argument :title, !types.String
 argument :description, !types.String
 argument :user, !types.Int

 type Types::BookType

 def call(_obj, args, _ctx)
  Book.create!(
   author: args[:author],
   title: args[:title],
   description: args[:description],
   user: args[:user]
   )
 end
end

然后在localhost:3000 / graphiql中执行以下操作:

mutation book {
 bookCreate(
  author: "Test", 
  title: "Book Test", 
  description: "Book Description", 
  user: 2) {
 id
 author
 title
 description
 }
}

获取以下信息:

<ActiveRecord::AssociationTypeMismatch: User(#69982231587660) expected, got 2 which is an instance of Integer(#11387600)>

我哪里出错了?

1 个答案:

答案 0 :(得分:0)

所以我将用户更改为user_id,然后在书本模型上做了:

belongs_to :user, foreign_key: 'user_id'

现在可以了。