Hello team,
I’ve been learning Elixir and Phoenix framework and am on my way to building my first app.
The app is structured as follows:
It has 2 separate contexts:
- Accounts context with Organizations and Users models
- TechCore context with Applications and Messages models.
The elixir file for the Applications model is as follows:
defmodule MyCoolApp.TechCore.Applications do
require Logger
use Ecto.Schema
import Ecto.Changeset
schema "applications" do
field :name, :string
field :api_token, :string
belongs_to :organizations, MyCoolApp.Accounts.Organizations
timestamps()
end
@doc false
def changeset(applications, attrs \\ %{}) do
applications
|> cast(attrs, [:name])
|> set_api_token_if_null()
|> validate_required([:name, :api_token])
end
defp set_api_token_if_null(changeset) do
token_ = get_field(changeset, :api_token)
if token_ do
changeset
else
put_change(changeset, :api_token, (:crypto.strong_rand_bytes(90) |> Base.encode64 |> binary_part(0, 80)))
end
end
end
The module for Organizations is as follows:
defmodule MyCoolApp.Accounts.Organizations do
use Ecto.Schema
import Ecto.Changeset
schema "organizations" do
field :name, :string
field :contact_email, :string
has_many :users, MyCoolApp.Accounts.Users
has_many :applications, MyCoolApp.TechCore.Applications
timestamps()
end
@doc false
def changeset(organizations, attrs) do
organizations
|> cast(attrs, [:name, :contact_email])
|> validate_required([:name, :contact_email])
end
end
Now comes the part that I do not understand.
When I try to create a new applications record like so:
%Applications{name: "App testing", organizations_id: 2} |> Applications.changeset(%{}) |> Repo.insert
The record is created (since the changeset function gets called).
However, when I try to create a record using build_assoc like so:
Repo.get_by!(Accounts.Organizations, id: 1) |> Ecto.build_assoc(:applications, name: "My New App") |> Repo.insert!
I get a not null violation error as follows:
** (Postgrex.Error) ERROR 23502 (not_null_violation) null value in column "api_token" violates not-null constraint
table: applications
column: api_token
Can someone please help me understand what I’m misunderstanding / doing wrong here please?