【问题标题】:Phoenix doesn't render associationsPhoenix 不呈现关联
【发布时间】:2019-12-16 00:35:58
【问题描述】:

我有一个简单的待办事项/作者/评论

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 时一切正常 但如果我想为待办事项添加 cmets 列表:

  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

key :name not found in: #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 在查询 todos 时看不到评论/作者关联,但在查询 cmets 时却看到了。

我为评论做了预加载:

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

知道这里发生了什么吗?

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

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

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

    这会为所有 ToDosComments 及其 Author 关联加载。

    【讨论】:

    • 我有 preload(:author) 和 preload(:cmets) 但是用你的版本替换 preload(:cmets) 是可行的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多