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
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.
0
Popular in Questions
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
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
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
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
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
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
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
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
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
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
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
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
I have an umbrella app.
Some of the apps inside depend on other apps in the umbrella, unsurprisingly.
I’m writing a test for one of the...
New
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
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible.
total = 10
while total != 0
...
New
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
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
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
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
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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









