2015-10-14 87 views
2

外生是給我上更新HAS_ONE關聯的錯誤:Ecto.Changeset相關模型誤差

模型的問題:

defmodule Something.Parent do 
    has_one :thing, Something.thing 

    @required_fields ~w(field1 field2 thing) 
end 

控制器更新動作

def update(conn, %{"id" => id, "parent" => parent_params}) do        
    parent = Repo.get!(Parent, id) |> Repo.preload(:thing) 

    changeset = Parent.changeset(parent, parent_params)               

    case Repo.update(changeset) do 
    {:ok, _parent} ->                    
     conn                      
     |> put_flash(:info, "Parent updated successfully")           
     |> redirect(to: parent_path(conn, :index))                    
    {:error, changeset} -> 
     render(conn, "edit.html", parent: parent, changeset: changeset) 
    end                
end 

PARAMS

parent =%{「some_number」=>「902」,「thing」=>%{「somethingfield」=>「blah」,「parent_id 「=>‘8’}

錯誤

you are attempting to change relation :thing of 
Whatever.Parent, but there is missing data. 

By default, if the parent model contains N children, at least the same 
N children must be given on update. In other words, it is not possible 
to orphan embed nor associated records, attempting to do so results 
in this error message. 

It is possible to change this behaviour by setting :on_replace when 
defining the relation. See `Ecto.Changeset`'s section on related models 
for more info. 

基於它看起來像父模式變更功能是在看到‘東西’從父成爲孤兒的文檔 - 但我不能明白爲什麼?

新建/創建操作工作得很好。

回答

2

這裏的問題是,你有一個thing與你正在改變的父母關聯。 - 當鑄造或操縱父變更當模型被替換的協會採取的行動on_replace:

隨着錯誤消息指出,您可以用has_one/3

on_replace選項進行更改。可能是:raise(默認),:mark_as_invalid,:nilify或者:delete。有關更多信息,請參閱相關模型的Ecto.Changeset章節。

Ecto.Changeset docs

+0

如果我想更改傳播會怎麼做:delete刪除以前的事情,用新的東西代替它? –

+0

@RichardHolland有幾個選項 - 我在答案中添加了更多詳細文檔的鏈接。 – Gazler

+0

謝謝。 :刪除得到我的願望 –