Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply_changes/1: convert nested schemaless validations #4516

Merged
merged 2 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2190,6 +2190,9 @@ defmodule Ecto.Changeset do
regardless if the changeset is valid or not. See `apply_action/2`
for a similar function that ensures the changeset is valid.

If a field of type `:map` contains a schemaless changeset,
its changes too will be applied and returned as a map with atom keys.

## Examples

iex> changeset = change(%Post{author: "bar"}, %{title: "foo"})
Expand All @@ -2208,6 +2211,9 @@ defmodule Ecto.Changeset do
{:ok, {tag, relation}} when tag in @relations ->
apply_relation_changes(acc, key, relation, value)

{:ok, :map} when is_struct(value, Changeset) ->
Map.put(acc, key, apply_changes(value))

{:ok, _} ->
Map.put(acc, key, value)

Expand Down
17 changes: 17 additions & 0 deletions test/ecto/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,23 @@ defmodule Ecto.ChangesetTest do
assert changed_post.category == nil
end

test "apply_changes/1 with nested schemaless validation" do
params = %{"seo_metadata" => %{"keywords" => ["foo", "bar"], "slug" => "my-post-1"}}

changeset =
%Post{}
|> changeset(params)
|> update_change(:seo_metadata, fn seo_metadata ->
{%{}, %{keywords: {:array, :string}, slug: :string}}
|> cast(seo_metadata || %{}, [:keywords, :slug])
|> validate_required([:keywords, :slug])
end)

changed_post = apply_changes(changeset)

assert changed_post.seo_metadata == %{keywords: ["foo", "bar"], slug: "my-post-1"}
end

describe "apply_action/2" do
test "valid changeset" do
post = %Post{}
Expand Down
Loading