DEV Community

Marcøs
Marcøs

Posted on • Edited on

Elixir setup - being consistent with schema

See Files on Github
common.ex
band.ex

It's typical to see timestamps() in every schema file, but what if you want to have the same primary key, schema prefix, or subset of columns in all the schema files.

First create your own using macro to handle the use/import statements along with any schema attributes.

  defmacro __using__(_) do
    quote do
      use Ecto.Schema
      import Ecto.Changeset
      import Portishead.Schema.Common

      @primary_key {:uuid, :binary_id, autogenerate: true}
      @schema_prefix "premarcos"
    end
  end
Enter fullscreen mode Exit fullscreen mode

Then define a macro that contains the common fields across all your schemas. You can use timestamps() or define your own date fields instead like created_at.

  defmacro common_fields do
    quote do
      # field :created_at, :utc_datetime_usec, autogenerate: {Ecto.Schema, DateTime.utc_now(), []}
      field :metadata, :string
      timestamps()
    end
  end
Enter fullscreen mode Exit fullscreen mode

Finally, in your schema file, use the module that was just created and call the common_fields macro.

defmodule Portishead.Schema.Band do
  use Portishead.Schema.Common

  schema "band" do
    common_fields()
  end
Enter fullscreen mode Exit fullscreen mode

Also worth reading

Top comments (0)