转换为JSON时预加载的数据丢失

时间:2018-04-03 00:05:32

标签: elixir phoenix-framework ecto

在我的上下文中,我有以下内容来预加载属于用户的所有者和受让人

  def list_tasks do
    Repo.all(Task)
    |> Repo.preload([:owner, :assignee])
  end

在我的索引控制器中我有这样的东西:

def index(conn, _params) do
    tasks = Issue.list_tasks()
    IO.inspect(tasks)
    render(conn, "index.json", tasks: tasks)
end

IO.inspect(tasks)打印出来

[
  %Task3.Issue.Task{
    __meta__: #Ecto.Schema.Metadata<:loaded, "tasks">,
    assignee: %Task3.Accounts.User{
      __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
      email: "Jill@Jill.com",
      id: 2,
      inserted_at: ~N[2018-04-02 18:22:21.699478],
      updated_at: ~N[2018-04-02 18:22:21.699486],
      username: "Jill"
    },
    assignee_id: 2,
    details: nil,
    id: 1,
    inserted_at: ~N[2018-04-02 18:22:21.711588],
    owner: %Task3.Accounts.User{
      __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
      email: "Jack@Jack.com",
      id: 1,
      inserted_at: ~N[2018-04-02 18:22:21.677877],
      updated_at: ~N[2018-04-02 18:22:21.677887],
      username: "Jack"
    },
    owner_id: 1,
    status: "COMPLETE",
    timespent: nil,
    title: "test",
    updated_at: ~N[2018-04-02 18:22:21.711598]
  }
]

然而,我在前端得到的json数据是

{"data":[{"title":"test","timespent":null,"status":"COMPLETE","id":1,"details":null}]}

我失去了受让人和老板。我错过了什么吗?是否需要采取额外步骤将预加载的数据转换为json格式?

1 个答案:

答案 0 :(得分:0)

您需要检查task_view.ex文件

如果它是使用phx.gen.json生成的默认文件,它将看起来像这样:

defmodule MyAppWeb.TaskView do
    use MyAppWeb, :view
    alias MyAppWeb.TaskView

    def render("index.json", %{tasks: tasks}) do
        %{data: render_many(tasks, TaskView, "task.json")}
    end

    def render("show.json", %{task: task}) do
        %{data: render_one(task, TaskView, "task.json")}
    end

    def render("task.json", %{task: task}) do
        %{
            id: task.id,
            title: task.title,
            timespent: task.timespent,
            details: task.details,
            status: task.status
        }
    end
end

您需要编辑此文件并添加要显示的额外字段。

e.g。对于assignee,您可以重复使用自动生成的视图:

defmodule MyAppWeb.TaskView do
    use MyAppWeb, :view
    alias MyAppWeb.{TaskView, AsigneeView}

    ...

    def render("task.json", %{task: task} do
        %{
            id: task.id,
            ...
            asignee: render_one(task.asignee, AsigneeView, "asignee.json"),
        }
    end
end