elixir - Phoenix 不呈现关联
问题描述
我有一个简单的待办事项/作者/评论
Todo has_many comments
Comment belongs_to Todo
Todo belongs_to Author
Author has_many todos
Author has_many comments
Comment belongs_to Author
如果我像这样渲染 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
当我访问时一切正常/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
我在 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
不知何故,Elixir 在查询待办事项时看不到评论/作者关联,但在查询评论时确实看到了。
我做了预加载评论:
comments = Repo.all(Comment) |> Repo.preload(:author)
知道这里发生了什么吗?
解决方案
从数据库中author
获取数据时是否预加载?todos
像这样的东西:
todos = Todo |> Repo.all() |> Repo.preload([comments: [:author]])
这会加载所有ToDos
与Comments
他们的Author
关联。
推荐阅读
- google-cloud-firestore - 从谷歌云功能将数据保存到firestore
- javascript - JavaScript:如果情况未填写,如何附加段落?
- httpclient - 最新版本的jar是否支持旧版本的jar
- java - 数组列表
与数组列表 ? - python - 如何在pytorch中动态索引张量?
- java - 有什么方法可以处理 API 调用返回的“数组响应”
- ajax - ajax 发布 API 403(禁止)
- html - Bootstrap 'align-content-around' 不起作用
- xml - 无法使用 XPath 将 XML 数据解析为 Java 对象
- sql - 将基表值与第二个表的值总和与 group by 进行比较