Maps merge but I get no user id on insert

Hey community,

When i try to insert my merged map with the current_user.id I get an error that my user id is not present.

My merged map looks like this:

%{
  content: "Testing the post mutation",
  published: false,
  title: "Test post",
  user_id: 3
}

The error looks like this

[error] #PID<0.427.0> running MediumGraphqlApiWeb.Endpoint (connection #PID<0.426.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: POST /api/graphiql
** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Enumerable not implemented for 
#Ecto.Changeset<action: :insert, changes: 
%{content: "Testing the post mutation", title: "Test post"}, 
errors: [user_id: {"can't be blank", [validation: :required]}]

Also my resolver looks like this

defmodule MediumGraphqlApiWeb.Resolvers.PostResolver do
  alias MediumGraphqlApi.Blog

  def create_post(_, %{input: input}, %{context: %{current_user: current_user}}) do
    post_input = Map.merge(input, %{user_id: current_user.id})
    IO.inspect(post_input)
    Blog.create_post(post_input)
  end
end

All other mutations work login register and list users

Thanks in advance

My bet would be to look at your post schema, and see if there is a belongs to user…

You might also show your post file.

Here is my post.ex(schema in a blog context)

defmodule MediumGraphqlApi.Blog.Post do
  use Ecto.Schema
  import Ecto.Changeset

  alias MediumGraphqlApi.Accounts.User

  schema "posts" do
    field :title, :string
    field :content, :string
    field :published, :boolean, default: false
    belongs_to(:user, User)

    timestamps()
  end

  @doc false
  def changeset(post, attrs) do
    post
    |> cast(attrs, [:title, :content, :published])
    |> validate_required([:title, :content, :published, :user_id])
  end
end

And here it is… You might add user_id to the list

3 Likes

Thanks, I missed that part