EctoIRS.Schema (ecto_irs v0.1.0)
View SourceEcto.Schema extensions for auditing capabilities.
This module provides the audits/2 macro that automatically adds audit fields
to your Ecto schemas for tracking who created or modified records.
Usage
First, add use EctoIRS.Schema to your schema module, then use the audits/2
macro to generate audit fields:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
schema "posts" do
field :title, :string
field :content, :text
# Generates :inserted_by and :updated_by associations
audits MyApp.User
timestamps()
end
endThis will add :inserted_by_id and :updated_by_id fields to your schema,
along with :inserted_by and :updated_by associations that reference the
specified type.
Custom Field Names
You can customize the field names:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
schema "posts" do
field :title, :string
audits MyApp.User,
inserted_by: :created_by,
updated_by: :modified_by
end
endDisabling Fields
You can disable either field by setting it to false:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
schema "posts" do
field :title, :string
# Only track who created, not who updated
audits MyApp.User, updated_by: false
end
endCustom References
If your referenced schema uses a custom primary key, specify it with the
:references option:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
schema "posts" do
field :title, :string
audits MyApp.User, references: :user_id
end
endAutogeneration
You can configure automatic population of audit fields using the
:autogenerate option with an MFA tuple:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
schema "posts" do
field :title, :string
audits MyApp.User, autogenerate: {MyApp.Context, :current_user_id, []}
end
endPre-configuration
You can pre-configure audit options using the @audits_opts module attribute:
defmodule MyApp.Post do
use Ecto.Schema
use EctoIRS.Schema
@audits_opts [autogenerate: {MyApp.Context, :current_user_id, []}]
schema "posts" do
field :title, :string
audits MyApp.User
end
end
Summary
Functions
Generates :inserted_by and :updated_by audit fields.
Functions
Generates :inserted_by and :updated_by audit fields.
The fields generated by this macro will automatically be set to the subject from the current context.
Options
:inserted_by- the Ecto schema name of the field for insertion times orfalseThe default value is:inserted_by.:updated_by- the Ecto schema name of the field for update times orfalseThe default value is:updated_by.:references(atom/0) - the field ontypethe audits reference:autogenerate(tuple ofatom/0,atom/0, list ofterm/0values) - an MFA tuple used for generating bothinserted_by_idandupdated_by_id
All options can be pre-configured by setting @audits_opts.