DEV Community

Marcøs
Marcøs

Posted on • Edited on

1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay