我打算仅使用Ecto
的Schema
和Changeset
进行验证,而无需将任何内容保存到数据库中,并试图弄清楚我应该使用Ecto.Schema.schema/2
还是Ecto.Schema.embedded_schema/1
。根据文档,它们之间的唯一区别是">嵌入式架构不需要源名称,并且不包含元数据字段。">
所以我选择了embedded_schema/1
,效果很好,但它让我想知道元数据到底是用来做什么的?Ecto.Schema.Metadata
文档对澄清这一点没有多大帮助:
存储结构的元数据。
这些字段是:
- state - 结构生存期中的状态,其中之一:built, :loaded, :删除
- 源 - 与查询一起的架构源 前缀,默认为 {nil, "源"}
- 上下文 - 由 数据库
搜索">元"不会产生任何结果,并且"元数据"在Ecto.Schema
文档中返回一个结果,该结果在上面引用的行中embedded_schema/1
。
忘记了 Ecto 3 即将推出,Hexdocs 文档仍然适用于 Ecto 2.2.11。在源代码中找到了更新的Metadata
文档,尽管它们更详细:
Stores metadata of a struct.
## State
The state of the schema is stored in the `:state`
field and allows following values:
* `:built` - the struct was constructed in
memory and is not persisted
to database yet;
* `:loaded` - the struct was loaded from database
and represents persisted data;
* `:deleted` - the struct was deleted and no longer
represents persisted data.
## Source
The `:source` tracks the (table or collection) where
the struct is or should be persisted to.
## Prefix
Tracks the source prefix in the data storage.
## Context
The `:context` field represents additional state some
databases require for proper updates of data. It is
not used by the built-in adapters of `Ecto.Adapters.Postres`
and `Ecto.Adapters.MySQL`.
## Schema
The `:schema` field refers the module name for the
schema this metadata belongs to.
(更新后的Schema
文档也解决了我上面的困境:
An Ecto schema is used to map any data source into an Elixir struct.
The definition of the schema is possible through two main APIs:
`schema/2` and `embedded_schema/1`.
`schema/2` is typically used to map data from a persisted source,
usually a database table, into Elixir structs and vice-versa. For
this reason, the first argument of `schema/2` is the source (table)
name. Structs defined with `schema/2` also contain a `__meta__` field
with metadata holding the status of the struct, for example, if it
has been built, loaded or deleted.
On the other hand, `embedded_schema/1` is used for defining schemas
that are embedded in other schemas or only exist in-memory. For example,
you can use such schemas to receive data from a command line interface
and validate it, without ever persisting it elsewhere. Such structs
do not contain a `__meta__` field, as they are never persisted.
(
Ecto.Schema.Metadata
仅用于存储所有与数据库相关的信息。
正如何塞在 Ecto 2 → 3 系列帖子中提到的那样,
自 Ecto2.0 以来,越来越多的开发人员和团队一直在使用 Ecto 进行数据映射和验证,而无需数据库。但是,将 Ecto 添加到您的应用程序中仍然会带来很多 SQL 包袱,例如适配器、沙箱和迁移,许多人认为这是一个混合的消息。
后者完全与元数据有关。
Ecto 2 有一个经验法则:是否需要后面的数据库表,请使用schema
;否则使用embedded_schema
。
旁注:我的一般建议是,当你想简单地理解一些东西时,不要阅读文档,阅读代码。
> Ecto 内部使用__meta__
字段来维护有关记录、关联的元数据,如果它们已加载、过时或更多。
您链接的文档中的描述似乎自给自足:
存储结构的元数据。
这些字段是:
state
- 结构生命周期中的状态,:built
之一,:loaded
,:deleted
source
- 架构的源以及查询前缀, 默认为{nil, "source"}
context
- 数据库存储的上下文