Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
Grocery Avatar asked Mar 25 '17 04:03

Grocery


2 Answers

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
like image 157
Dogbert Avatar answered Sep 30 '22 18:09

Dogbert


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
like image 23
Tsutomu Avatar answered Sep 30 '22 20:09

Tsutomu