Phoenix不提供关联

时间:2019-12-13 12:26:04

标签: elixir phoenix-framework

我有一个简单的Todo / Author / Comment

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在查询待办事项时看不到Comment / Author关联,但是在查询评论时却看到了。

我预先加载了评论:

comments = Repo.all(Comment) |> Repo.preload(:author)

你知道这里发生了什么吗?

1 个答案:

答案 0 :(得分:5)

从数据库中获取author时是否预加载了todos? 像这样:

todos = Todo |> Repo.all() |> Repo.preload([comments: [:author]])

这会为其所有ToDos关联的CommentsAuthor加载。