1
我有下面的Ecto模型。當我渲染時,我希望JSON用屬性名稱「layers」替換「tilemap_layers」。Poison.Encoder如何重命名呈現的JSON中的屬性?
我的應用程序中有很多'圖層'類型,所以當我創建我的數據庫模式時,我需要創建一個唯一命名的模式。但是,此JSON將由第三方客戶端使用,必須將其命名爲「圖層」。
這樣做的建議方法是什麼?
該模型是在這裏:
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
再次感謝Gazler!我正在嘗試foreign_key選項,因爲這是我真正想要的 –
Woot!這工作!我確實需要改變一個小的錯字。我改變了foreign_key :: tilemap_id –
@JoshPetitt你可能不需要實際指定'foreign_key'。你可以試試嗎? – Gazler