2016-02-19 6 views
8

Sto provando a scrivere un singolo changeset che aggiornerà un modello e inserirà un'associazione. Non riesco a trovare esempi su come utilizzare put_assoc/4Ecto: Come aggiornare e inserire l'associazione in un aggiornamento utilizzando put_assoc

order = order 
    |> Proj.Order.changeset(%{state: "error", error_count: order.error_count + 1}) 
    |> Ecto.Changeset.put_assoc(
     :order_errors, 
     [Proj.OrderError.changeset(%Proj.OrderError{}, %{reason: "not_found"})]) 
    |> Proj.Repo.update! 

Questo stampa il seguente errore:

** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid. 

* Changeset changes 

%{order_errors: [%Ecto.Changeset{action: :insert, changes: %{id: nil, inserted_at: nil, order_id: nil, reason: "not_found", updated_at: nil}, constraints: [], errors: [order_id: "can't be blank"], filters: %{}, model: %Proj.OrderError{__meta__: #Ecto.Schema.Metadata<:built>, id: nil, inserted_at: nil, order: #Ecto.Association.NotLoaded<association :order is not loaded>, order_id: nil, reason: nil, updated_at: nil}, optional: [], opts: [], params: %{"reason" => "not_found"}, prepare: [], repo: nil, required: [:order_id, :reason], types: %{id: :id, inserted_at: Ecto.DateTime, order_id: :id, reason: :string, updated_at: Ecto.DateTime}, valid?: false, validations: []}], state: "error"} 

* Changeset params 

%{"error_count" => 1, "state" => "error"} 

* Changeset errors 

[] 

Eventuali esempi che posso guardare per put_assoc/4? Come posso scoprire perché il changeset non è valido?

L'obiettivo di fare le cose in questo modo è che spero che il nuovo order abbia order_errors precaricato.

risposta

5

Ho trovato come farlo funzionare nel Ecto tests. Breve storia, è sufficiente rimuovere la creazione changeset e utilizzare direttamente un nuovo modello.

order = order 
    |> Proj.Order.changeset(%{state: "error", error_count: order.error_count + 1}) 
    |> Ecto.Changeset.put_assoc(
     :order_errors, 
     [%Proj.OrderError{reason: "not_found"}]) 
    |> Proj.Repo.update! 

mi piace ancora di sapere come capire il messaggio di errore dal post originale

Problemi correlati