Integer does not match type :id

I’m trying to insert a changeset into the database with this struct:

%{"address" => "asdf", "apt" => "asdfa", "city" => "asdf", "state" => "asdf", "user_id" => 2, "zip" => "asdf"}

but I get the error

value %{"address" => "asdf", "apt" => "asdfa", "city" => "asdf", "state" => "asdf", "user_id" => 2, "zip" => "asdf"} for Mm.Orders.Order.user_id in insert does not match type :id

I’m taking the user_id from the conn and updating the params like so:

def create(
        %{private: %{:plug_session => %{"user" => user_id}}} = conn,
        %{"order" => order_params}
      ) do
    user_order_params = Map.update(order_params, "user_id", user_id, & &1)

    case Orders.create_order(user_order_params) do
      {:ok, order} ->
        |> put_flash(:info, "Order created successfully.")
        |> redirect(to: Routes.order_path(conn, :show, order))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)

My schema looks like

schema "orders" do
... fields
belongs_to :user, User

What am I missing here? The user_id is an integer. Whats the difference between type id and a type integer?


Seems like you are passing a map instead of an integer. Try inspecting user_order_params.

1 Like

This is what I get back from inspecting user_order_params:

  "address" => "asdf",
  "apt" => "asdfa",
  "city" => "asdf",
  "state" => "asdf",
  "user_id" => 2,
  "zip" => "asdf"

Should I be using something like cast_assoc or put_assoc?

I tried just inserting order_params and I get the same error

 value %{"address" => "asdf", "apt" => "asdfa", "city" => "asdf", "state" => "asdf", "zip" => "asdf"}` for Mm.Orders.Order.user_id in insert does not match type :id

I’ve found my error, I was already accounting for inserting a user_id into the changeset in the Orders context, though this may not be the best implementation, I’m undecided.

  def create_order(attrs \\ %{}, user_id) do
    |> Order.changeset(attrs)
    |> Ecto.Changeset.put_change(:user_id, user_id)
    |> Repo.insert()
1 Like