首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Poison.Encoder如何预加载关联?

Poison.Encoder如何预加载关联?
EN

Stack Overflow用户
提问于 2015-11-17 11:47:57
回答 1查看 1.8K关注 0票数 2

下面是经济学模型。当我试图渲染时,我会得到一个错误。我如何修改“派生”以使其能够预加载?还是我必须写出实现?建议的处理方法是什么?

代码语言:javascript
复制
** (RuntimeError) cannot encode association :tilemap_layers from MyProject.Tilemap to JSON because the association was not loaded. Please make sure you have preloaded the association or remove it from the data to be encoded

模型如下:

代码语言:javascript
复制
defmodule MyProject.Tilemap do
  use MyProject.Web, :model

  @derive {Poison.Encoder, only: [
    :name,
    :tile_width,
    :tile_height,
    :width,
    :height,
    :orientation,
    :tilemap_layers,
    :tilesets
  ]}

  schema "tilemaps" do

    field :name, :string
    field :tile_width, :integer
    field :tile_height, :integer
    field :width, :integer
    field :height, :integer
    field :orientation, :string

    has_many :tilemap_layers, MyProject.TilemapLayer
    has_many :tilesets, MyProject.Tileset

    timestamps
  end

  @required_fields ~w(tile_width tile_height width height)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-17 11:56:34

简单地说,你不应该。预装数据不是视图层的责任。

当您获取资源时(通常是控制器或从控制器调用的函数),您应该执行预加载。

例如,使用预加载/3

代码语言:javascript
复制
def index(_conn, _params)
  timemaps = Tilemap |> Repo.all() |> Repo.preload(:timemap_layers)
  render("index.json", tilemaps: tilemaps)
end

还可以在使用预加载/3的查询中执行预加载。

代码语言:javascript
复制
query = from t in Tilemap,
  preload: [:tilemap_layers]
Repo.all(query)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33756142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档