Ecto.Changeset.cast/4

Parsed documentation:
View on GitHub
Converts the given `params` into a changeset for `model`
keeping only the set of `required` and `optional` keys.

This functions receives a model and some `params`, and casts the `params`
according to the schema information from `model`. `params` is a map with
string keys or a map with atom keys containing potentially unsafe data.

During casting, all valid parameters will have their key name converted to an
atom and stored as a change in the `:changes` field of the changeset.
All parameters that are not listed in `required` or `optional` are ignored.

If casting of all fields is successful and all required fields
are present either in the model or in the given params, the
changeset is returned as valid.

## Empty parameters

The `params` argument can also be the atom `:empty`. In such cases, the
changeset is automatically marked as invalid, with an empty `:changes` map.
This is useful to run the changeset through all validation steps for
introspection.

## Composing casts

`cast/4` also accepts a changeset instead of a model as its first argument.
In such cases, all the effects caused by the call to `cast/4` (additional and
optional fields, 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.

Note that if a field is marked both as *required* as well as *optional* (for
example by being in the `:required` field of the argument changeset and also
in the `optional` list passed to `cast/4`), then it will be marked as required
and not optional). This represents the fact that required fields are
"stronger" than optional fields.

## Examples

    iex> changeset = cast(post, params, ~w(title), ~w())
    iex> if changeset.valid? do
    ...>   Repo.update!(changeset)
    ...> end

Passing a changeset as the first argument:

    iex> changeset = cast(post, %{title: "Hello"}, ~w(), ~w(title))
    iex> new_changeset = cast(changeset, %{title: "Foo", body: "Bar"}, ~w(title), ~w(body))
    iex> new_changeset.params
    %{title: "Foo", body: "Bar"}
    iex> new_changeset.required
    [:title]
    iex> new_changeset.optional
    [:body]
Suggestions:
Please help! Open an issue on GitHub if this assessment is incorrect.