Reputation: 1044
This is partly a GraphQL question, and partly a Rails application architecture question.
So lets say I'm creating a company blog, and I have 3 database models: Post, Author, and Tag. A post has_many authors and tags, and an author has_many posts. All relations are many-to-many.
I have a graphql request that looks something like this:
mutation {
createPost(
title: "foo"
description:"bar"
author: {
name: "author1"
}
tags:
[{content: "tag1"}]
) {
post {
id
}
errors
}
}
}
And here is my mutation. This code works for the post
creation, but I'm not sure how to approach the creation of the associated records.
module Mutations
class CreatePost < Mutations::BaseMutation
argument :title, String, required: true
argument :description, String, required: true
argument :author, [Types::AuthorInputType], required: false
argument :tags, [Types::TagInputType], required: false
field :post, Types::PostType, null: true
field :errors, [String], null: true
def resolve(title:, description:, author:, tags:)
post = Post.new({title: title, description: description})
# I want to find or create the tags and author here, and create any neccesary records and associations
# Should that be done here? If so, how? And if not, where would this logic live instead?
if post.save
{
post: post,
errors: [],
}
else
{
user: nil,
errors: post.errors.full_messages
}
end
end
end
end
Upvotes: 2
Views: 558
Reputation: 718
I actually wrote about this (and more) a few months ago: A Complete Guide to Setting up a GraphQL Server on Rails .
This method of organizing code is working out well for us on our open-source project - Pupilfirst.
Upvotes: 1