Created
December 15, 2022 01:18
-
-
Save dmkit/9182d70bdfd8b72f6da62f685d84df4f to your computer and use it in GitHub Desktop.
[Elixir][Ecto] Copy an existing Ecto struct (Repo.build_from/1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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