2

Ecto 在更新 has_one 关联时给我一个错误:

有问题的型号:

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

参数

父 = %{"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.

根据文档,父模型上的变更集函数看起来像是从父模型中分离出来的“事物”——但我不明白为什么?

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

4

2 回答 2

2

这里的问题是您thing与要更改的父级有关联。

正如错误消息所指定的,您可以使用has_one/3on_replace选项更改它

:on_replace - 在转换或操作父变更集时替换模型时对关联采取的操作。可能是 :raise(默认)、:mark_as_invalid、:nilify 或 :delete。有关更多信息,请参阅 Ecto.Changeset 的相关模型部分。

Ecto.Changeset 文档

于 2015-10-14T22:29:21.887 回答
1

这是 Ecto 中的一个错误。使用此提交在 master 上修复。

https://github.com/elixir-lang/ecto/commit/6c1c04304ebecf5ccae4a49008deab814e034d2b

于 2015-10-16T00:56:33.237 回答