Sup,我正在学习 Ecto,我正在尝试将具有关联的记录插入到另一个表中。它有点工作,因为正在插入记录但外键字段为空。
代码:
parent = Repo.get(Hangman.MasterCat, parent_id)
changeset = build(parent, :categories)
|> Category.changeset( params)
IO.inspect(changeset)
if changeset.valid? do
Repo.insert(changeset)
json conn, ResponseUtils.jsonResponse(true)
else
json conn, ResponseUtils.jsonResponse(false,["parents doesn't exist"])
end
检查变更集
%Ecto.Changeset{action: nil, changes: %{name: "Kategory 1"}, constraints: [],
errors: [], filters: %{},
model: %{__meta__: #Ecto.Schema.Metadata<:built>, __struct__: Hangman.Category,
id: nil, inserted_at: nil, master_cat_id: 1,
mastercat: #Ecto.Association.NotLoaded<association :mastercat is not loaded>,
mastercat_id: nil, name: nil, updated_at: nil,
words: #Ecto.Association.NotLoaded<association :words is not loaded>},
optional: [], opts: [], params: %{"name" => "Kategory 1"}, repo: nil,
required: [:name],
types: %{id: :id, inserted_at: Ecto.DateTime, mastercat_id: :id, name: :string,
updated_at: Ecto.DateTime,
words: {:assoc,
%Ecto.Association.Has{cardinality: :many, defaults: [], field: :words,
on_cast: :changeset, on_delete: :nothing, on_replace: :raise,
owner: Hangman.Category, owner_key: :id, queryable: Hangman.Word,
related: Hangman.Word, related_key: :category_id}}}, valid?: true,
validations: []}
我可以看到出于某种奇怪的原因,它将父 ID 分配给字段 master_cat_id 而不是 mastercat_id。
任何帮助深表感谢。 https://github.com/Hajto/hangmanelixir