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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay