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
PARAMS
parent =%{" some_number" => " 902","东西" => %{" 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.
根据文档,看起来父模型上的变更集功能正在看到' Thing'从父母那里成为孤儿 - 但我不明白为什么?
新的/创建动作效果很好。
答案 0 :(得分:2)
这里的问题是您有一个与您正在更改的父级相关联的thing
。
如错误消息所指定,您可以使用has_one/3
的on_replace
选项对其进行更改
:on_replace - 在转换或操作父变更集时替换模型时对关联采取的操作。可能是:raise(默认值),: mark_as_invalid,:nilify或:delete。有关详细信息,请参阅Ecto.Changeset的相关模型部分。
答案 1 :(得分:1)
这是Ecto中的一个错误。使用此提交修复了master。
https://github.com/elixir-lang/ecto/commit/6c1c04304ebecf5ccae4a49008deab814e034d2b