Why field is getting changed?

Hi all
Look at the following code from https://hexdocs.pm/ecto/Ecto.Changeset.html#cast/4 about cast function:

iex> changeset = cast(post, %{title: "Hello"}, [:title])
iex> new_changeset = cast(changeset, %{title: "Foo", body: "Bar"}, [:body])
iex> new_changeset.params
%{"title" => "Foo", "body" => "Bar"}

Why the title is going to changed to Foo? On second line, it tells only the body field is going to be change!

Thanks

1 Like

That isn’t what the [:body] list means. It means "Cast the :body parameter into the changeset. If there is already changes casted into the changeset, it’s just added to that. This is covered in the docs you linked:

cast/3 also accepts a changeset as its first argument. In such cases, all the effects caused by the call to cast/3 (additional errors and changes) are simply added to the ones already present in the argument changeset.

1 Like

While elixir does let you chain changesets so you can leverage piping, the docs are incorrect.

The second cast specified that :body is the only value that can be updated based on the params provided, so :title will be ignored. This makes sense functionally which leads me to believe that it is a simple typo.

I added a PR for this here: https://github.com/elixir-ecto/ecto/pull/1958/files

2 Likes