halostatue

halostatue

Using Repo.insert_all when your schema has embeds_many

Not so much a question as a discovery. This is true as of Ecto 2.2. If you need to perform an insert_all and the target schema has embeds_many to an embedded_schema…here’s how to make it work.

defmodule ImageTest do
  defmodule Image do
    use Ecto.Schema
    import Ecto

    embedded_schema do
      field :url, :string
      field :purpose, :string
      field :color, :string
    end

    def changeset(image, attrs), do: cast(image, attrs, [:url, :color, :purpose])
  end

  use Ecto.Schema
  import Ecto

  defmodule Migration do
    use Ecto.Migration

    def change do
      create table(:image_test, primary_key: false) do
        add :id, :binary_id, primary_key: true
        add :images, :jsonb, null: false, default: fragment("'{}'::jsonb")
      end
    end
  end

  schema "image_test" do
    embeds_many :images, Image

    timestamps()
  end

  @required_fields ~w(images)a

  def changeset(struct, params), do: cast(struct, params, @required_fields)
end

# Assumes a `Repo`.
images1 = [%{url: "giphy.com"}, %{color: "blue"}]
images2 = [%{url: "imgur.com"}, %{color: "red"}]

# This won’t work
# Repo.insert_all(ImageTest, %{images: images1, images2})

images1 = Enum.map(images1, &struct(ImageTest.Image, &1))
images2 = Enum.map(images2, &struct(ImageTest.Image, &1))
# This works.
Repo.insert_all(ImageTest, %{images: images1, images2})

It feels weird that this is what we have to do for this to work, but I’m happy to have discovered it.

First Post!

ragamuf

ragamuf

THANK YOU!!!

I have been struggling with insert_all with an embed and could not resolve the error:

** (Ecto.ChangeError) value {:ok, %{...}} for ... in insert_all does not match type {:embed, %Ecto.Embedded{cardinality: :one, field: :preferences, on_cast: nil, on_replace: :update, ordered: true, owner: …, related: …, unique: true}}

Casting the embed changeset changes back to a struct within the insert_all operation solved it.

Where Next?

Popular in Questions Top

johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New

We're in Beta

About us Mission Statement