How to check if struct is persisted or not?
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