Does `virtual: true` have any effect with an embedded schema?

Viewed 352

The documentation for Ecto.Schema says the following about the :virtual option:

:virtual - When true, the field is not persisted to the database.

The embedded_schema/1 function says that it describes a schema kept exclusively in-memory. (i.e. It is never persisted to the DB.) Does that mean that for embedded schemas, the :virtual option has no effect?

1 Answers

The documentation on Ecto.Schema.#embedded_schema/1 actually says:

An embedded schema is either embedded into another schema or kept exclusively in memory. For this reason, an embedded schema does not require a source name and it does not include a metadata field.

When embedded into another schema, it acts as a snippet directly injected into the target schema, and :virtual fields act as usual.

When kept in memory, :virtual fields do still

  • allow optional skip of type check by declaring type :any, unlike other fields
  • not listed in __schema__(:fields)
  • not support querying for type with __schema__(:type, field)
  • not support :autogenerate nor :read_after_writes options
Related