How to add multiple foreign keys to one data structure using build_assoc?

Hello everyone, I am a beginner Elixir developer and I don’t know a lot.

I’m thinking about how to add multiple foreign keys to one data structure using build_assoc

Let’s look at an example:

I have - employee, organization and location.

An employee has the following fields:

  • id
  • Name
  • phone number
  • organization ID
  • location ID

In my multi transaction, an organization is created, then a location is created, and lastly, an employee is created.

During a transaction, we store the results of previous operations.

The problem is this:
After we create the organization and location, I want to take their id and put it in the worker through build_assoc.

How can I do that? In my understanding, we can only add 1 id via build_assoc.

Are there other ways?

My colleagues do this directly. That is, they put the ID through Map.put

I’d like to find a more elegant solution like build_assoc

build_assoc/3 accepts a third optional attributes parameter for this purpose:

build_assoc(organization, :employees, location_id:

P.S. Don’t forget to set foreign key constraints on the database level for data consistency.


Thank you! You saved my day!

1 Like