Skip to content

Commit

Permalink
fixed for non-regular primary key
Browse files Browse the repository at this point in the history
  • Loading branch information
devvit authored and devvit committed Feb 16, 2018
1 parent ea407dc commit a0f5dbf
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
14 changes: 11 additions & 3 deletions lib/paper_trail.ex
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ defmodule PaperTrail do
%Version{
event: "insert",
item_type: model.__struct__ |> Module.split() |> List.last(),
item_id: model.id,
item_id: get_model_id(model),
item_changes: serialize(model),
originator_id:
case originator_ref do
Expand All @@ -322,7 +322,7 @@ defmodule PaperTrail do
%Version{
event: "update",
item_type: changeset.data.__struct__ |> Module.split() |> List.last(),
item_id: changeset.data.id,
item_id: get_model_id_from_changeset(changeset),
item_changes: changeset.changes,
originator_id:
case originator_ref do
Expand All @@ -342,7 +342,7 @@ defmodule PaperTrail do
%Version{
event: "delete",
item_type: model.__struct__ |> Module.split() |> List.last(),
item_id: model.id,
item_id: get_model_id(model),
item_changes: serialize(model),
originator_id:
case originator_ref do
Expand Down Expand Up @@ -378,4 +378,12 @@ defmodule PaperTrail do

defp add_prefix(changeset, nil), do: changeset
defp add_prefix(changeset, prefix), do: Ecto.put_meta(changeset, prefix: prefix)

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
4 changes: 2 additions & 2 deletions lib/paper_trail/version_queries.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ defmodule PaperTrail.VersionQueries do
@spec get_versions(record :: Ecto.Schema.t(), options :: []) :: Ecto.Query.t()
def get_versions(record, options) when is_map(record) do
item_type = record.__struct__ |> Module.split() |> List.last()
version_query(item_type, record.id, options) |> @repo.all
version_query(item_type, PaperTrail.get_model_id(record), options) |> @repo.all
end

@doc """
Expand Down Expand Up @@ -75,7 +75,7 @@ defmodule PaperTrail.VersionQueries do
@spec get_version(record :: Ecto.Schema.t(), options :: []) :: Ecto.Query.t()
def get_version(record, options) when is_map(record) do
item_type = record.__struct__ |> Module.split() |> List.last()
last(version_query(item_type, record.id, options)) |> @repo.one
last(version_query(item_type, PaperTrail.get_model_id(record), options)) |> @repo.one
end

@doc """
Expand Down

0 comments on commit a0f5dbf

Please sign in to comment.