Skip to content

Instantly share code, notes, and snippets.

@dmkit
Created December 15, 2022 01:18
Show Gist options
  • Save dmkit/9182d70bdfd8b72f6da62f685d84df4f to your computer and use it in GitHub Desktop.
Save dmkit/9182d70bdfd8b72f6da62f685d84df4f to your computer and use it in GitHub Desktop.
[Elixir][Ecto] Copy an existing Ecto struct (Repo.build_from/1)
defmodule Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
def build_from(struct) do
struct = Ecto.put_meta(struct, state: :built)
:primary_key
|> struct.__struct__.__schema__()
|> List.foldl(struct, &(Map.put(&2, &1, nil)))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment