Ecto embeds_many without id
Asked Answered
L

1

5

Is there any way to used embeds_many in Ecto without having an id / primary_key field?

My database depends on having a unique index on this field, and ecto automatically inserting keys breaks this requirement.

Luddite answered 15/8, 2016 at 3:53 Comment(0)
U
9

Yes. embeds_many in Postgres ends up as an array of JSON. Define a module that represents that JSON data and in the definition of the embedded_schema use @primary_key false. For example, suppose you wanted to store an array of key/value pairs on each row. Let's call them Tags. You could define that like below and you'd have no generated primary key on each element in the array. You could have another field within that schema which would be populated in whatever way makes sense for your app.

  defmodule MyApp.Tag do
  use MyApp.Web, :model

  @primary_key false
  embedded_schema do
    field :key, :string
    field :value, :string
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:key, :value])
    |> validate_required([:key])
  end
end
Undressed answered 11/6, 2017 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.