How to handle association with embedded_schema..?

When embedding many schemas embeds_many how can we manage associations with another table?

if i have:

defmodule Order do
  use Ecto.Schema

  schema "orders" do
    field :name, :string

    embeds_many :items, Item do
      field :name, :string
      field :price,  :integer
    end
  end
end

and i want the item_id to be associated to another table. how to manage it? like that?

def change do
    create table(:payments) do
      add :label, :string
     add :item_id, references(:items, on_delete: :delete_all),
                          null: false

      timestamps()
    end

    create unique_index(:payments, [:label])
    create index(:payments, [:item_id])
  end

You can’t. Associations are at the database level handled by foreign keys and only table rows can be associated by a foreign key. Embedded schemas don’t have their own table rows.

ok. but “embedded” by default set their primary key type to :binary_id …isn’t it?
anyway i have to correct that and chose the “query” option!

It’s a primary key for ecto, but not for the database. For the database a primary key must be a real column.

2 Likes

These Ecto issues are probably relevant here: