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
    |> cast(params, @required_fields)
    |> put_assoc(:users, user)
    |> validate_required([:name])
    |> unique_constraint(:name)

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} ->
        |> put_flash(:info, "#{} created!")
        |> redirect(to: model_path(conn, :index))
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)

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

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