phoebe

phoebe

Build_assoc and UUID

Hi, I’ve been scratching my head around this for a while and trying different combinations, but I’m just stuck whilst using build_assoc which does not recognise binary id UUIDs in my code. Here’s my problem and question.

I’m working on a banking app, so I have a user and wallet. user was created with Pow if that makes any difference. There is a has_many relationship between user and wallet. Here are the schemas:

use MyApp.Schema

schema "users" do
  field :role, :string, null: false, default: "user"
  has_many :wallets, MyApp.Accounts.Wallet
  pow_user_fields()
  timestamps()
end

and

use MyApp.Schema
...
schema "wallets" do
  field :description, :string
  field :balance, Money.Ecto.Composite.Type
  belongs_to :user_id, MyApp.Users.User, references: :uuid, type: :binary_id
  timestamps()
end

where MyApp.Schema is set up for UUIDs:

defmodule MyApp.Schema do
  defmacro __using__(_) do
    quote do
      use Ecto.Schema
      @primary_key {:uuid, :binary_id, autogenerate: true}
      @foreign_key_type :binary_id
      @derive {Phoenix.Param, key: :uuid}
      @timestamps_opts
    end
  end
end

Then in my CreateWallet migration:

defmodule MyApp.Repo.Migrations.CreateWallets do
  use Ecto.Migration

  def change do
    create table(:wallets) do
      add :description, :string, null: false
      add :balance, :money_with_currency, null: false
      add :user_id, references(:users, column: :uuid, type: :binary_id, on_delete: :nothing)
      timestamps()
    end

    create index(:wallets, [:user_id])
  end
end

All standard I think so far. However, if I want to implement a create_user_wallet function:

def create_user_wallet(%User{} = user, %{} = wallet_params) do
  wallet = Ecto.build_assoc(user, :wallets, wallet_params)
  Repo.insert(wallet)
end

and then try to run it, there is an error:

** (KeyError) key :user_uuid not found
    (ecto 3.7.1) lib/ecto/association.ex:754: Ecto.Association.Has.build/3

This is fine if it’s referring to the uuid key in the user map, as I don’t see user_uuid there, it’s just %User{uuid: "1234..."} - or is it referring to user_id in the wallet database? However, why should the build_assoc function expect that and not function as is given the Schema implementation and how can I override it, or set up my schemas and/or own Schema implementation and/or migration correctly?

Thanks for reading this far!

Most Liked

al2o3cr

al2o3cr

The errors you are getting suggest that you have a column named user_uuid on the wallets table. You’ll need to tell the belongs_to / has_many machinery about that:

# in the user schema
has_many :wallets, foreign_key: :user_uuid

# in the wallet schema
belongs_to :user, foreign_key: :user_uuid, ...etc

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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 47930 226
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement