Ecto table naming convention? Table name with underscore like Company_Type?

I was using phoenix generators for schema and html and the model files in change set and file name have double underscores.

I renamed the file and the changeset I just delete the extra underscore.

It doesn’t seem to affect anything. Not sure if it’s a bug or I’m naming my table wrong.

I’m just curious is there a naming scheme/convention for relational table in Ecto?

Thanks in advance

1 Like

Your tables can have any name you want. The convention (I believe inherited from Rails) is that it should be the plural of your schema. Currently, I am using a legacy database (20 years old) and I have a schema named CatalogItem using a table named catgeneral.

defmodule MedikEcto.Admin.Catalog do
  use Ecto.Schema, :model
  import Ecto.Changeset

  @primary_key false
  @derive {Phoenix.Param, key: :catalog_id}

  schema "catgeneral" do
    field :catalog_id, :string, primary_key: true, source: :catalogid
    field :item_description, :string, source: :itemdescription
    field :item_id, :string, primary_key: true, source: :itemid
    field :status, :string, source: :status
    field :status_web, :string, source: :statusweb
    field :user_id, :string, source: :userid

    timestamps(inserted_at: :transactiondate, updated_at: :lastupdatedate)
  end

  @doc false
  def changeset(catalog, attrs) do
    catalog
    |> cast(attrs, [:catalog_id, :item_id, :item_description, :user_id, :status, :status_web])
    |> validate_required([
      :catalog_id,
      :item_id,
      :item_description,
      :user_id,
      :status,
      :status_web
    ])
  end
end

Notice that the table columns are “aliased” using the source: keyword so I can use nice underscored field names in my code. Also, the primary key is not an integer nor named id. Finally the timestamps are named transactiondate and lastupdatedate instead of inserted_at and updated_at

3 Likes