gyc*_*gyc 3 elixir phoenix-framework
我有一个简单的 Todo/作者/评论
Todo has_many comments
Comment belongs_to Todo
Todo belongs_to Author
Author has_many todos
Author has_many comments
Comment belongs_to Author
Run Code Online (Sandbox Code Playgroud)
如果我像这样渲染 todo_view.ex:
def render("todo.json", %{todo: todo}) do
%{id: todo.id,
title: todo.title,
description: todo.description,
date: todo.date,
author: author_json(todo.author)}
end
defp author_json(author) do
%{name: author.name}
end
Run Code Online (Sandbox Code Playgroud)
当我访问时一切正常/api/todos,/api/comments
但是如果我想添加待办事项的评论列表:
def render("todo.json", %{todo: todo}) do
%{id: todo.id,
title: todo.title,
description: todo.description,
date: todo.date,
author: author_json(todo.author),
comments: render_many(todo.comments, CommentView, "comment.json")}
end
Run Code Online (Sandbox Code Playgroud)
我在 comment_view.ex 中收到 KeyError
键:名称未在以下位置找到:#Ecto.Association.NotLoaded
def render("comment.json", %{comment: comment}) do
%{id: comment.id,
content: comment.content,
author: author_json(comment.author)}
end
defp author_json(author) do
%{name: author.name}
end
Run Code Online (Sandbox Code Playgroud)
不知何故,Elixir 在查询待办事项时看不到评论/作者关联,但在查询评论时确实看到了。
我做了评论的预加载:
comments = Repo.all(Comment) |> Repo.preload(:author)
Run Code Online (Sandbox Code Playgroud)
知道这里发生了什么吗?
从数据库中author获取时是否进行了预加载todos?像这样的东西:
todos = Todo |> Repo.all() |> Repo.preload([comments: [:author]])
Run Code Online (Sandbox Code Playgroud)
加载对所有ToDos的Comments与他们的Author关联。