Elixir 如何预加载关联?
我有下面的外胚层模型。当我试图渲染时,我得到一个错误。我如何修改@derive使其能够预加载?还是我必须写下实施方案?建议的处理方法是什么Elixir 如何预加载关联?,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我有下面的外胚层模型。当我试图渲染时,我得到一个错误。我如何修改@derive使其能够预加载?还是我必须写下实施方案?建议的处理方法是什么 ** (RuntimeError) cannot encode association :tilemap_layers from MyProject.Tilemap to JSON because the association was not loaded. Please make sure you have preloaded the associati
** (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
模型如下:
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
简而言之,你不应该这样做。预加载数据不是视图层的责任 在获取资源(通常是控制器或从控制器调用的函数)时,应该执行预加载 例如,使用: 您还可以使用以下命令在查询中执行预加载:
谢谢你,加兹勒,现在说得通了!
def index(_conn, _params)
timemaps = Tilemap |> Repo.all() |> Repo.preload(:timemap_layers)
render("index.json", tilemaps: tilemaps)
end
query = from t in Tilemap,
preload: [:tilemap_layers]
Repo.all(query)