Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto embeds_many without id

Tags:

ecto

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.

like image 952
Ben Smith Avatar asked Aug 15 '16 03:08

Ben Smith


1 Answers

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
like image 184
fmcgeough Avatar answered Nov 06 '22 14:11

fmcgeough