From 2ced4a299577531363a880be40bcdee16ab08959 Mon Sep 17 00:00:00 2001 From: devvit Date: Sat, 17 Feb 2018 02:52:59 +0800 Subject: [PATCH] fixed for non-regular primary key with test --- lib/paper_trail.ex | 6 +----- .../20170525133833_create_uuid_products.exs | 7 +++++++ test/paper_trail/uuid_test.exs | 11 +++++++++++ test/support/uuid_models.exs | 18 ++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/lib/paper_trail.ex b/lib/paper_trail.ex index d07d60ec..ee099e97 100644 --- a/lib/paper_trail.ex +++ b/lib/paper_trail.ex @@ -322,7 +322,7 @@ defmodule PaperTrail do %Version{ event: "update", item_type: changeset.data.__struct__ |> Module.split() |> List.last(), - item_id: get_model_id_from_changeset(changeset), + item_id: get_model_id(changeset.data), item_changes: changeset.changes, originator_id: case originator_ref do @@ -382,8 +382,4 @@ defmodule PaperTrail do def get_model_id(model) do Map.get(model, List.first(model.__struct__.__schema__(:primary_key))) end - - def get_model_id_from_changeset(changeset) do - get_model_id(changeset.data) - end end diff --git a/priv/uuid_repo/migrations/20170525133833_create_uuid_products.exs b/priv/uuid_repo/migrations/20170525133833_create_uuid_products.exs index f14a5820..579685ba 100644 --- a/priv/uuid_repo/migrations/20170525133833_create_uuid_products.exs +++ b/priv/uuid_repo/migrations/20170525133833_create_uuid_products.exs @@ -8,5 +8,12 @@ defmodule PaperTrail.UUIDRepo.Migrations.CreateUuidProducts do timestamps() end + + create table(:items, primary_key: false) do + add :item_id, :binary_id, primary_key: true + add :title, :string, null: false + + timestamps() + end end end diff --git a/test/paper_trail/uuid_test.exs b/test/paper_trail/uuid_test.exs index a4f67f65..8947680e 100644 --- a/test/paper_trail/uuid_test.exs +++ b/test/paper_trail/uuid_test.exs @@ -14,6 +14,7 @@ defmodule PaperTrailTest.UUIDTest do repo().delete_all(Version) repo().delete_all(Admin) repo().delete_all(Product) + repo().delete_all(Item) :ok end @@ -47,4 +48,14 @@ defmodule PaperTrailTest.UUIDTest do assert version.admin == admin end + + test "versioning models that have a non-regular primary key" do + item = + %Item{} + |> Item.changeset(%{title: "hello"}) + |> PaperTrail.insert!() + + version = Version |> last |> repo().one + assert version.item_id == item.item_id + end end diff --git a/test/support/uuid_models.exs b/test/support/uuid_models.exs index 635ce457..92d09373 100644 --- a/test/support/uuid_models.exs +++ b/test/support/uuid_models.exs @@ -34,3 +34,21 @@ defmodule Admin do |> validate_required([:email]) end end + +defmodule Item do + use Ecto.Schema + import Ecto.Changeset + + @primary_key {:item_id, :binary_id, autogenerate: true} + schema "items" do + field(:title, :string) + + timestamps() + end + + def changeset(model, params \\ %{}) do + model + |> cast(params, [:title]) + |> validate_required(:title) + end +end