PhoenixMTM v1.0.0 PhoenixMTM.Changeset View Source

Provides many_to_many helpers for Ecto Changesets.

The following example schema demonstrates how you would configure the functionality of our examples below.

Example Schema

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

Link to this section Summary

Functions

Cast a collection of IDs into a many_to_many association using a custom lookup function

Cast a collection of IDs into a many_to_many association

Link to this section Functions

Link to this function

cast_collection(set, assoc, lookup_fn) View Source

Cast a collection of IDs into a many_to_many association using a custom lookup function.

Your custom lookup function is expected to receive a list of ids, and should return a list of records matching those ids.

The custom lookup function is the perfect place to re-map the list of ids, such as casting each to Integer.

Example

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
Link to this function

cast_collection(set, assoc, repo, mod) View Source

Cast a collection of IDs into a many_to_many association.

This function assumes:

  • The column on your associated table is called id.

Example

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