Ecto many to many insert with has_many :through

Apologies if this has been asked before - my googling has failed me.

I currently have three tables in my DB: Orders, Items, and OrderItems.

Orders and Items have a many to many relationship, joined through OrderItems. I’m having trouble inserting
Orders and OrderItems at the same time. I’ve tried using cast_assoc and put_assoc but these haven’t worked.

schema "orders" do
    ...

    has_many :order_items, OrderItems
    has_many :items, through: [:order_items, :item]

    ...

    timestamps()
  end
  schema "order_items" do
    belongs_to :order, Order, primary_key: true
    belongs_to :item, Item, primary_key: true

    field :size, :string
    field :params, :map
    timestamps()
  end

The table “items” does not contain any has_many rows as I do not need to access the relationship from this way.

How would be best to create and insert records for both orders and order_items at the same time?

1 Like