11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ElixirAdvent Calendar 2023

Day 4

スキーマに仮想フィールド(virtual field)を追加する

Last updated at Posted at 2023-12-25

Finally, schemas can also have virtual fields by passing the virtual: true option. These fields are not persisted to the database and can optionally not be type checked by declaring type :any.

virtual: true オプションを渡すことで、スキーマに仮想フィールドを含めることができます。
DBに保存する必要はないが、構造体としてフィールドがあってほしいときに使ったりします。
DBの変更はしないのでマイグレーションの必要はありません。

defmodule NaiveTree.Categories.Category do
  use Ecto.Schema
  import Ecto.Changeset

  schema "categories" do
    field :name, :string
    field :parent_id, :id
    field :depth, :integer, virtual: true
    field :serial_number, :string, virtual: true # <- これ

    timestamps()
  end

  @doc false
  def changeset(category, attrs) do
    category
    |> cast(attrs, [:name])
    |> validate_required([:name])
  end
end

11
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?