Trouble with many_to_many association

I’m trying to create a many_to_many association but I keep getting an invalid error on the attribute after using put_assoc

def changeset(model, user, params \\ :invalid) do
    model
    |> cast(params, @required_fields)
    |> put_assoc(:users, user)
    |> validate_required([:name])
    |> unique_constraint(:name)
  end

After adding the put_assoc it gives the error

#Ecto.Changeset<action: nil, changes: %{name: "Name"},
 errors: [users: {"is invalid", [type: {:array, :map}]}], data: #MyApp.MyModel<>,
 valid?: false>

In the controller I have this

def create(conn, %{"mymodel" => params}, user) do
    changeset = MyModel.changeset(%MyModel{}, user, params)

    case Repo.insert(changeset) do
      {:ok, model} ->
        conn
        |> put_flash(:info, "#{model.name} created!")
        |> redirect(to: model_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def action(conn, _) do
    apply(__MODULE__, action_name(conn), [conn, conn.params, conn.assigns.current_user])
  end

I’m trying to add an association to the current user when MyModel is created using the connection assignment of current_user.

I’ve checked user and it is returning the correct user schema. Does anyone know why it’s being marked as invalid?

iirc put_assoc expects a list if it is a m2m, so you might try passing [user]

1 Like

Thank you!!! That fixed it.

1 Like