John_Shelby

John_Shelby

Map embed schema for changeset - take data from one structure and save it on a similar structure

Hello everyone,

I’m trying to take data from one structure and save it on a similar structure when creating a record through function.

My data is saved fine as long as I don’t send data from embed schema answers.Can someone please advise me how to properly send data from embed schema please? I thought I could work with answers as another atom, but I can’t.

I have this error: expected changeset data to be a Elixir.MyApp.AssessmentAppPipelines.AssessmentAppPipeline.AssessmentAnswer struct, got: %MyApp.AssessmentPipelines.AssessmentPipeline.AssessmentAnswer{id: "05bcf97a-84ed-478f-a74a-b6da9aa2a28f", title: "T1", score: 2, answ_id: nil, delete: nil}

Structure is:
Schema_A has_many Schema_B embeds_many Embed_Schema_C
create →
Schema_D has_many Schema_E embeds_many Embed_Schema_F

Function:

  def create_assessment_app_pipeline_from_assessment_pipeline(
        %AssessmentPipeline{} = assessment_pipeline,
        attrs \\ %{}
      ) do
    attrs
    |> Map.merge(%{
      "assessment_pipeline_id" => assessment_pipeline.id,
      "questions" =>
        Enum.map(assessment_pipeline.assessment_questions, fn m ->
          m
          |> Map.from_struct()
          |> Map.take([:question, :description, :category, :multiple_choice, :assessment_answers])
        end),
        .
        .
        .
       "count_of_questions" => length(assessment_pipeline.assessment_questions)
    })
    |> create_assessment_app_pipeline()
  end

  def create_assessment_app_pipeline(attrs \\ %{}) do
    %AssessmentAppPipeline{}
    |> AssessmentAppPipeline.changeset(attrs)
    |> Repo.insert()
  end

I have these schemas:

Pipeline

  schema "assessment_app_pipelines" do
    field :progress, :integer, default: 0
    field :status, AssessmentAppPipeline.Status, default: :draft
    field :submitted_at, :naive_datetime
    field :evaluation, :integer, default: 0
    field :count_of_evaluations, :integer, default: 0
    field :count_of_questions, :integer, default: 0
    .
    .
    .


    timestamps()

    belongs_to :company, Company
    belongs_to :assessment_pipeline, AssessmentPipeline
    has_many :questions, AssessmentAppPipeline.Question
    .
    .
    .
  end

  def changeset(assessment_app_pipeline, attrs) do
    assessment_app_pipeline
    |> cast(attrs, [
      :company_id,
      :assessment_pipeline_id,
      :count_of_questions
    ])
    |> put_assoc(:questions, Map.get(attrs, "questions"))
    |> validate_required([
      :questions,
      :company_id,
      :assessment_pipeline_id
    ])
    |> unique_constraint(:company_id,
      name: :assessment_app_pipelines_company_id_assessment_pipeline_id_index
    )
  end

Question

  schema "assessment_app_pipeline_questions" do
    field :question, :string
    field :description, :string
    field :category, :string
    field :multiple_choice, :boolean, default: false

    embeds_many :assessment_answers,  MyApp.AssessmentAppPipelines.AssessmentAppPipeline.AssessmentAnswer, on_replace: :delete

    belongs_to :assessment_app_pipeline, MyApp.AssessmentAppPipelines.AssessmentAppPipeline,
      type: :binary_id

    belongs_to :updated_by, MyApp.Users.User, type: :binary_id

    timestamps()
  end

  def changeset(question, attrs) do
    question
    |> cast(attrs, [
      :question,
      :description,
      :category,
      :answer,
      :updated_by_id,
      :multiple_choice
    ])
    |> cast_embed(:assessment_answers, with: &MyApp.AssessmentAppPipelines.AssessmentAppPipeline.AssessmentAnswer.changeset/2, required: true)
    |> validate_required([
    .
    .
    .
    ])
  end

Embed schema

  embedded_schema do
    field :title, :string
    field :score, :integer
    field :selected, :boolean
  end

  def changeset(assessment_answer, attrs) do
    assessment_answer
    |> cast(attrs, [:title, :score, :selected])
    |> validate_required([:title, :score])
  end

If you need more information I will add.

Thanks for any help! :slight_smile:

Most Liked

al2o3cr

al2o3cr

I suspect the assessment_answers here is the root cause: the loaded MyApp.AssessmentPipelines.AssessmentPipeline.AssessmentAnswer structs are being passed along unaltered, while cast_assoc expects either string-keyed maps or MyApp.AssessmentAppPipelines.AssessmentAppPipeline.AssessmentAnswer structs.

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
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

We're in Beta

About us Mission Statement