yanniskatsaros

yanniskatsaros

Hello! :wave: Relatively new to Elixir, and brand new Phoenix LiveView & Ecto user here.

(Using: Elixir 1.17.1 and Phoenix LiveView 1.0.0-rc.6.)

At a high level, my question boils down to:

How can I insert/create a new record in the database using Ecto when one of the schema fields is a belongs_to association, and the given value already exists in the database?

Please see the code provided below for the full context, but I’d like to be able to create a new user by providing an existing organization, not create a new associated organization.

I have run the Phoenix authentication generator for LiveView (mix phx.gen.auth) and am in the process of making tweaks to the generated schema to suit my project needs. Namely, I have the following simple structure:

  • an organization can have many users associated with it
  • a user can only belong to a single organization

I have mapped these relationships out using the following two modules (I have omitted other functions in each module for brevity):

The users schema (this is what was generated from mix phx.gen.auth and has been modified for my requirements):

# lib/example/accounts/user.ex

defmodule Example.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "users" do
    field :email, :string
    field :password, :string, virtual: true, redact: true
    field :hashed_password, :string, redact: true
    field :current_password, :string, virtual: true, redact: true
    field :confirmed_at, :utc_datetime

    belongs_to :organization, Example.Accounts.Organization

    timestamps(type: :utc_datetime)
  end
end

The organizations schema:

# lib/example/accounts/organization.ex
defmodule Example.Accounts.Organization do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "organizations" do
    field :name, :string
    field :active, :boolean, default: true
    has_many :users, Example.Accounts.User

    timestamps(type: :utc_datetime)
  end
end

This is how I’ve currently solved the issue, but I feel like it’s unnecessary to first query the Organization simply as a way to use it in the User for the Repo.insert() changeset (since I already have the organization UUID)

# (simplified example)

def register_user(attrs) when is_map(attrs) do
  # example `attrs`
  # %{"email" => "name@example.com", "organization_id" => "7051b9fd-cb24-41ba-b5ca-79cd257612ff", "password" => "[FILTERED]"}
  organization = get_organization!(attrs["organization_id"])

  %User{organization: organization}
  |> cast(attrs, [:email, :password])
  |> validate_required([:organization])
  |> validate_email(opts)
  |> validate_password(opts)
  |> Repo.insert()
end

This approach works but I’m not sure it’s the recommended approach for this pattern. Can someone please help point me in the right direction or offer some advice on the canonical way to achieve this (if this is not correct)? Thanks so much in advance!

Showing Posts 1 to 3

muelthe

muelthe

Hey there, welcome! If I understand what you’re aiming at, the docs here should give you a good starting point: Associations — Ecto v3.14.0

And maybe more specific: Associations — Ecto v3.14.0

Hermanverschooten

Hermanverschooten

the belongs_to adds a organization_id field to your schema, you can just cast that.

yanniskatsaros

yanniskatsaros OP

Thank you very much! That seemed to do the trick. Simple and effective, I appreciate it.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews