我有这个带有has_many
指令的模型。我正在尝试从中获取所有值并将它们显示在 json 响应中:
defmodule Heroico.Datacenter do
use Heroico.Web, :model
@derive {Poison.Encoder, only: [:id, :identifier, :city, :state, :country]}
schema "datacenters" do
field :identifier, :string
field :city, :string
field :state, :string
field :country, :string
belongs_to :provider, Heroico.Provider
has_many :plans, Heroico.Plan
timestamps()
end
...
end
控制器:
def index(conn, _params, _current_user, _claims) do
render conn, "index.json", datacenters: Repo.all(Datacenter)
end
看法:
defmodule Heroico.DatacenterView do
use Heroico.Web, :view
def render("index.json", %{datacenters: datacenters}) do
%{datacenters: datacenters}
end
end
lib/poison_encoder.ex
:
defimpl Poison.Encoder, for: Any do
def encode(%{__struct__: _} = struct, options) do
map = struct
|> Map.from_struct
|> sanitize_map
Poison.Encoder.Map.encode(map, options)
end
defp sanitize_map(map) do
Map.drop(map, [:__meta__, :__struct__])
end
end
如您所见,@derive
明确指出只[:id, :identifier, :city, :state, :country]
应编码但我似乎无法摆脱此错误:
cannot encode association :plans from Heroico.Datacenter 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