Search code examples
phoenix-frameworkecto

How to check if struct is persisted or not?


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?


Solution

  • 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