I found it’s not easy to update nested schema when the type is an array.
The shape of my schemal
DB
create table(:templates) do
add :name, :string
add :surveys, {:array, :map}
Template schema
schema “templates” do
field(:name, :string)
embeds_many(:surveys, Survey)
The survey Schema
embedded_schema do
field(:data, :map)
timestamps()
end
The update method
def add_survey_to_template(uuid, params) do
template = Repo.get(Template, uuid)
survey =
%Survey{}
|> Survey.changeset(params)
template
|> change()
|> put_embed(:surveys, [survey | template.surveys])
|> Repo.update()
I have to query curre first, then append new survey to the array column.
The issue is
- Addtional query ops
2.If multiple user do this concurrently, the final result is wrong.
The other approach is by using
push
- pushes (appends) the given value to the end of the array field
from(u in User, update: [push: [tags: “cool”]])
But this is not work for embeds_many fields.
Any other good idea?