Embedded resources are stored as maps in attributes of other resources. They are great for storing structured data, and support a whole range of useful features that resources support. For example, you can have calculations, validations, policies and even relationships on embedded resources. Here is an example of a simple embedded resource:
By default, all fields on an embedded resource will be included in the data layer, including keys with nil values. To prevent this, add the `embed_nil_values?` option to `use Ash.Resource`. For example:
This will call the primary `update` action on the resource. This allows you to define an action on the embed, and add validations to it. For example, you might have something like this:
```elixir
defmodule MyApp.Profile do
use Ash.Resource,
data_layer: :embedded # Use the atom `:embedded` as the data layer.
Remember: default actions are already implemented for a resource, with no need to add them. They are called `:create`, `:update`, `:destroy`, and `:read`. You can use those without defining them. You only need to define them if you wish to override their configuration.
All values in the original array are destroyed, and all maps in the new array are used to `create` new records.
## Adding a primary key
Adding a primary key to your embedded resources is especially useful when managing lists of data. Specifically, it allows you to consider changes to elements with matching primary key values as `updates`.
validate {Increasing, field: :counter}, on: :update
end
end
```
Now, you can accept input meant to `update` individual list items. The entire list must still be provided, but any items with a matching id will be considered an `update` instead of a `destroy` + `create`.
### Determining what action(s) will be called with a primary key:
Identities can be added on an embedded resource, which will ensure that for any given list, they are unique on that identity. For example, if you had an embedded resource called `Tag`, you could add an identity on `name` to ensure that nothing has duplicate tag names.
to specify a type (but not queries/mutations) for an embedded resource. If you do, instead of being treated as a `:json` type it will get its own named input object type and field type.
## Accessing the source changeset
When building changesets for embedded resources, the source changeset will be available in action changes under `changeset.context.__source__`.