phoenix_mtm v0.4.0 PhoenixMTM.Changeset

Provides many_to_many helpers for Ecto Changesets.

Summary

Functions

Cast a collection of IDs into a many_to_many association

Functions

cast_collection(set, assoc, lookup_fn)
cast_collection(set, assoc, repo, mod)

Cast a collection of IDs into a many_to_many association.

Example

schema "models" do
  many_to_many :tags, App.Tag,
    join_through: App.TagToModel,
    on_delete: :delete_all,
    on_replace: :delete
end

def changeset(struct, params \ %{}) do
  struct
  |> cast(params, ~w())
  |> PhoenixMTM.Changeset.cast_collection(:tags, App.Repo, App.Tag)
end

Passing a custom collection lookup function

def changeset(struct, params \ %{}) do
  struct
  |> cast(params, ~w())
  |> PhoenixMTM.Changeset.cast_collection(:tags, fn ids ->
    # Convert Strings back to Integers
    ids = Enum.map(ids, &String.to_integer/1)

    App.Repo.all(from t in App.Tag, where: t.id in ^ids)
  end)
end