diff --git a/lib/alog.ex b/lib/alog.ex index 5d782d7..31244a8 100644 --- a/lib/alog.ex +++ b/lib/alog.ex @@ -243,6 +243,19 @@ defmodule Alog do User.all() """ def all do + # get the oldest items + sub = + from(m in __MODULE__, + distinct: m.entry_id, + order_by: [asc: :inserted_at], + select: m + ) + + query = from(m in subquery(sub), where: not m.deleted, select: m) + + oldest_items = @repo.all(query) + + # get the most recent inserted items, ie desc: :inserted_at sub = from(m in __MODULE__, distinct: m.entry_id, @@ -253,6 +266,14 @@ defmodule Alog do query = from(m in subquery(sub), where: not m.deleted, select: m) @repo.all(query) + |> Enum.map(fn(newest_item) -> + oldest_item = Enum.find(oldest_items, &(&1.entry_id == newest_item.entry_id)) + if oldest_item do + %{newest_item | inserted_at: oldest_item.inserted_at} + else + newest_item + end + end) end @doc """ diff --git a/test/all_test.exs b/test/all_test.exs index 6b89cdf..791e3bb 100644 --- a/test/all_test.exs +++ b/test/all_test.exs @@ -14,9 +14,10 @@ defmodule AlogTest.AllTest do test "does not include old items" do {:ok, user} = %User{} |> User.changeset(Helpers.user_1_params()) |> User.insert() {:ok, _} = %User{} |> User.changeset(Helpers.user_2_params()) |> User.insert() - {:ok, _} = user |> User.changeset(%{postcode: "W2 3EC"}) |> User.update() + {:ok, user_updated} = user |> User.changeset(%{postcode: "W2 3EC"}) |> User.update() assert length(User.all()) == 2 + assert user.inserted_at == user_updated.inserted_at end end end