Is there a way to figure out if struct is persisted or not? I started digging source for Ecto's insert_or_update
but with no luck as it hits some private method. I want to accoplish something like this:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:whatever]
|> do_a_thing_on_unsaved_struct
end
defp do_a_thing_on_unsaved_struct(struct) do
case ARE_YOU_PERSISTED?(struct) do
:yes -> struct
:no -> do_things(struct)
end
end
Is it possible, or I'm doing something dumb?
You can check the .__meta__.state
of the struct. If it's a new one (not persisted), it'll be :built
, and if it was loaded from the database (persisted), it'll be :loaded
:
iex(1)> Ecto.get_meta(%Post{}, :state)
:built
iex(2)> Ecto.get_meta(Repo.get!(Post, 1), :state)
:loaded
You can check struct.data.id
if the struct's primary key is id
:
defp do_a_thing_on_unsaved_struct(struct) do
if struct.data.id, do: struct, else: do_things(struct)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With