Elixir 在exto.Query上的exto.Schema中自动设置虚拟字段

Elixir 在exto.Query上的exto.Schema中自动设置虚拟字段,elixir,ecto,Elixir,Ecto,在“链接时间”中,演讲者描述了如何通过如下转换函数管道化变更集,基于虚拟字段自动设置EXTO.Schema中的字段: defmodule MusicDb.Track do use Ecto.Schema schema "tracks" do field :title, :string field :duration, :integer field :duration_string, :string, virtual: true timestamps()

在“链接时间”中,演讲者描述了如何通过如下转换函数管道化变更集,基于虚拟字段自动设置EXTO.Schema中的字段:

defmodule MusicDb.Track do
  use Ecto.Schema

  schema "tracks" do
    field :title, :string
    field :duration, :integer
    field :duration_string, :string, virtual: true

    timestamps()
  end

  def changeset(track, attrs) do
    track
    |> validate...
    |> convert_duration_string
  end
end
例如,这用于将3:25的用户输入转换为205


我怎么做的另一个方向?当我从
Repo
查询
Track
时,虚拟字段
duration\u string
nil
。如何安装一个函数,以便在查询某个结构的架构时自动计算和设置虚拟字段?

根据需要,您可以将任何此类计算字段添加到序列化程序中(例如,
dempl Jason.Encoder
),或者,您可以在抽象模块中定义必要的修饰(例如,在凤凰城背景下)。来自长生不老药论坛的讨论可能与以下内容相关: