Search code examples
elixirphoenix-frameworkecto

How to return result in last line by pipe operator?


Can I return time_stamp in last line without extracting it in curly brackets?

{:ok, time_stamp} = Myapp.Repo.insert(changeset) # |> Map.get time_stamp
time_stamp

# {:ok, %Myapp.TimeStamp{__meta__: #Ecto.Schema.Metadata<:loaded>, active: true...}

Solution

  • You can use Kernel.elem/2 to get an item from a tuple by index (starting from 0).

    Myapp.Repo.insert(changeset) |> elem(1)
    

    However if your changeset is not valid then this will return the changeset, as an invalid changeset will return {error, changeset}

    If you could explain a little bit about why you want to do this then we may be able to help further.