Ecto.Changeset.cast
cast
, go back to Ecto.Changeset module for more information.
Specs
cast( Ecto.Schema.t() | t() | {data(), types()}, %{required(binary()) => term()} | %{required(atom()) => term()} | :invalid, [atom()], Keyword.t() ) :: t()
Applies the given params
as changes for the given data
according to
the given set of permitted
keys. Returns a changeset.
The given data
may be either a changeset, a schema struct or a {data, types}
tuple. The second argument is a map of params
that are cast according
to the type information from data
. params
is a map with string keys
or a map with atom keys containing potentially invalid data.
During casting, all permitted
parameters whose values match the specified
type information will have their key name converted to an atom and stored
together with the value as a change in the :changes
field of the changeset.
All parameters that are not explicitly permitted are ignored.
If casting of all fields is successful, the changeset is returned as valid.
Note that cast/4
validates the types in the params
, but not in the given
data
.
Options
:empty_values
- a list of values to be considered as empty when casting. Empty values are always replaced by the default value of the respective key. Defaults to[""]
Examples
iex> changeset = cast(post, params, [:title])
iex> if changeset.valid? do
...> Repo.update!(changeset)
...> end
Passing a changeset as the first argument:
iex> changeset = cast(post, %{title: "Hello"}, [:title])
iex> new_changeset = cast(changeset, %{title: "Foo", body: "World"}, [:body])
iex> new_changeset.params
%{"title" => "Hello", "body" => "World"}
Or creating a changeset from a simple map with types:
iex> data = %{title: "hello"}
iex> types = %{title: :string}
iex> changeset = cast({data, types}, %{title: "world"}, [:title])
iex> apply_changes(changeset)
%{title: "world"}
Composing casts
cast/4
also accepts a changeset as its first argument. In such cases, all
the effects caused by the call to cast/4
(additional errors and changes)
are simply added to the ones already present in the argument changeset.
Parameters are merged (not deep-merged) and the ones passed to cast/4
take precedence over the ones already in the changeset.