EctoMorph.generate_changeset
generate_changeset
, go back to EctoMorph module for more information.
Specs
generate_changeset(map() | ecto_struct(), schema_module() | ecto_struct()) :: Ecto.Changeset.t()
Casts the given data into a changeset according to the types defined by the given schema
. It
ignores any fields in data
that are not defined in the schema, and recursively casts any embedded
fields to a changeset also. Accepts a different struct as the first argument, calling Map.to_struct
on it first. Also allows the schema to be an existing struct, in which case it will infer the schema
from the struct, and effectively update that struct with the changes supplied in data.
Examples
...> data = %{
...> "integer" => "77",
...> "steamed_hams" => [%{
...> "pickles" => 1,
...> "sauce_ratio" => "0.7",
...> "double_nested_schema" => %{"value" => "works!"}
...> }],
...> }
...> EctoMorph.generate_changeset(data, %SchemaUnderTest{integer: 2})
...>
Specs
generate_changeset(map(), schema_module() | ecto_struct(), list()) :: Ecto.Changeset.t()
Takes in a map of data and creates a changeset out of it by casting the data recursively, according to the whitelist of fields in fields. The map of data may be a struct, and the fields whitelist can whitelist fields of nested relations by providing a list for them as well.
Examples
If we provide a whitelist of fields, we will be passed a changeset for the changes on those fields only:
...> data = %{
...> "integer" => "77",
...> "steamed_hams" => [%{
...> "pickles" => 1,
...> "sauce_ratio" => "0.7",
...> "double_nested_schema" => %{"value" => "works!"}
...> }],
...> }
...> EctoMorph.generate_changeset(data, SchemaUnderTest, [:integer])
...>
We can also define whitelists for any arbitrarily deep relation like so:
...> data = %{
...> "integer" => "77",
...> "steamed_hams" => [%{
...> "pickles" => 1,
...> "sauce_ratio" => "0.7",
...> "double_nested_schema" => %{"value" => "works!"}
...> }],
...> }
...> EctoMorph.generate_changeset(data, SchemaUnderTest, [
...> :integer,
...> steamed_hams: [:pickles, double_nested_schema: [:value]]
...> ])