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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With