Attached.Ecto.Changeset (Attached v0.1.1)

Copy Markdown View Source

Changeset integration for attached fields.

Automatically imported into schemas that use Attached.Ecto.Schema, so you call put_attached/3 directly inside your changeset/2 function:

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  use Attached.Ecto.Schema

  import Ecto.Changeset

  schema "users" do
    field :name, :string
    attached :avatar
    timestamps()
  end

  def changeset(user, attrs) do
    user
    |> cast(attrs, [:name])
    |> put_attached(:avatar, attrs["avatar"])
  end
end

The upload is deferred to prepare_changes/2 so the original insert and the storage upload run inside the same transaction as the parent insert/update. A failed parent insert rolls the original row back with it; the orphaned storage file is swept up by Attached.Originals.PurgeOrphansWorker.

Summary

Functions

Attaches an upload to an attached field on the changeset.

Functions

put_attached(changeset, field, original)

Attaches an upload to an attached field on the changeset.

Accepts:

  • %Plug.Upload{} structs
  • Maps with :path and :filename keys (e.g. from Phoenix.LiveView.consume_uploaded_entries/3)
  • Attached.Originals.Original structs (re-attach an existing original — no storage I/O, just sets the FK)
  • nil — no-op, preserves the existing attachment