arekanderu

arekanderu

How can I insert a new record in Phoenix/Ecto and update the foreign key in another Schema?

Hello!

I have a Phoenix v1.7.2 service and I am trying to do the following with Ecto and a Postgres datatabase.

I have simplified the code a little bit for brevity.

lib/helloworld/user.ex

defmodule HelloWorld.User do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "users" do
    belongs_to :company, Company

    timestamps()
  end

  @doc false
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:id])
    |> validate_required([:id])
  end
end
priv/repo/migrations/20211023161717_create_users.ex

defmodule HelloWorld.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :company_id, :binary_id

      timestamps()
    end

    create index("users", [:company_id])
  end
end
lib/helloworld/company.ex

defmodule HelloWorld.Company do
  use Ecto.Schema
  import Ecto.Changeset

  alias HelloWorld.User

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

  schema "companies" do
    field :name, :string

    has_many :user, User
    belongs_to :owner, User

    timestamps()
  end

  @doc false
  def changeset(company, attrs) do
    company
    |> cast(attrs, [:owner_id, :name])
    |> validate_required([:owner_id, :name])
  end
end
priv/repo/migrations/20211023161718_create_companies.ex

defmodule HelloWorld.Repo.Migrations.CreateCompanies do
  use Ecto.Migration

  def change do
    create table(:companies, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :owner_id, references(:users, type: :binary_id, on_delete: :nothing), null: false
      add :name, :string, null: false

      timestamps()
    end

    create index("companies", [:owner_id])
  end
end
priv/repo/migrations/20211023161719_add_companies_users_association.ex

defmodule HelloWorld.Repo.Migrations.AddCompaniesUsersAssociation do
  use Ecto.Migration

  def change do
    alter table(:users, primary_key: false) do
      modify :company_id, references(:companies, type: :binary_id, on_delete: :nothing)
    end
  end
end

In summary for the db structure:

  • I have a companies table
  • I have a users table
  • Each company can have many users as members
  • Each company can have only ONE user as owner
  • Each user can belong to ONE company

In my scenario, a user might already exists in my database with users.company_id null. At some point a user creates a company, and what I wish to achieve is to 1) insert the company in the dabatae 2) the user in users table, that matches the inserted company’s owner_id field, to be updated and get the company_id of the newly inserted company.

I only have this at the moment and not sure what to change, even though I tried plenty of things,

alias HelloWorld.Company

def create_company(attrs \\ %{}) do
    %Company{}
    |> Company.changeset(attrs)
    # Update somehow the `company_id` field from the associated row on users table
    # matching the `attrs["owner_id"]`
    |> Repo.insert()
  end

I am not sure if it’s possible to do this with schema associations or if I have to do the whole thing with Ecto.Multi.

Thank you for your time.

Marked As Solved

tfwright

tfwright

There are probably a few different ways to achieve this but I would strongly suggest using Multi to keep things more explicit.

Also Liked

arekanderu

arekanderu

Thanks for the link. I read it actually yesterday (among plenty of other articles and Ecto guides) but I wasn’t able to figure out how to do it.

tfwright

tfwright

I’m not exactly sure what you mean by “with schema associations,” but I can’t think of an implementation using put_assoc that wouldn’t be too awkward to be worth trying out. cast_assoc is explicitly not intended for things like this. prepare_changes would work very similarly to the example in the docs. Get the new id from the company changeset, find the user and update the attribute.

But again want to emphasize I would consider these abuses of those functions when Multi is available.

Where Next?

Popular in Questions Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48475 226
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New

We're in Beta

About us Mission Statement