Home Posts Tags Post Search Tag Search

Post 12

Game Site Journal - 03

Published on: 2025-04-12 Tags: elixir, Blog, Side Project, LiveView, Game Site, Ecto, Authorization, User Name
For this post I wanted to go over the way you can add in a new column for a table, specifically for adding in a User Name for the authorization table in my Game Site. First an foremost you must you the command line to create a new migration (you could always manully do this but start here).

mix ecto.new.migration the_name_for_the_migration_or_what_it_does

This will created a timestamped file under priv/repo/migrations

Within this file you could add and other table (create table(:name)) or in this case we will alter a table with the following

def change do
    alter table(:users) do
      add :user_name, :string, null: false
    end
  end

Once this is done we need to alter the schema for the table.

schema "users" do
...
    field :user_name, :string
...

Then we need to be sure that we cast the information as well as be sure that the name is not taken.

def registration_changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:email, :password, :user_name]) # be sure to add in :user_name
    ...
    |> unsafe_validate_unique(:user_name, Blog.Repo)
    |> unique_constraint(:user_name, message: "Name taken")
  end

The last 2 line will make sure that you are not adding in a used name. The first of the 2 will allow the changeset to check the data.base for the name.

We now need to change the user creation page and allow for the new field.

<.simple_form
        for={@form}
        id="registration_form"
        phx-submit="save"
        phx-change="validate"
        phx-trigger-action={@trigger_submit}
        action={~p"/users/log_in?_action=registered"}
        method="post"
...
        <.input field={@form[:email]} type="email" label="Email" required />
        <.input field={@form[:password]} type="password" label="Password" required />
        <.input field={@form[:user_name]} type="text" label="User Name" required />
...
      </.simple_form>

The last line is the new field.

So long as you have all the correct settings from above you should have a new column for your User db.