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

[WIP]: Allow cast schemaless embeds #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
16 changes: 16 additions & 0 deletions lib/ecto/changeset/relation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ defmodule Ecto.Changeset.Relation do
end
end

def cast(%{related: nil} = relation, owner, params, current, on_cast) do
fun = &do_cast(relation, owner, &1, &2, &3, &4, on_cast)

with :error <- cast_or_change(relation, params, current, fn _ -> [] end, fn _ -> [] end, fun) do
{:error, {"is invalid", [type: expected_type(relation)]}}
end
end

def cast(%{related: mod} = relation, owner, params, current, on_cast) do
pks = mod.__schema__(:primary_key)
fun = &do_cast(relation, owner, &1, &2, &3, &4, on_cast)
Expand All @@ -125,6 +133,14 @@ defmodule Ecto.Changeset.Relation do
do_cast(meta, owner, params, struct, allowed_actions, idx, on_cast)
end

defp do_cast(%{related: nil} = relation, _owner, params, nil = _struct, allowed_actions, idx, on_cast) do
{:ok,
relation
|> apply_on_cast(on_cast, %{}, params, idx)
|> put_new_action(:insert)
|> check_action!(allowed_actions)}
end

defp do_cast(relation, owner, params, nil = _struct, allowed_actions, idx, on_cast) do
{:ok,
relation
Expand Down
44 changes: 44 additions & 0 deletions test/ecto/changeset/schemaless_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
defmodule Ecto.Changeset.SchemalessTest do
use ExUnit.Case, async: true

defmodule Author do
import Ecto.Changeset

@types %{
name: :string,
age: :integer,
book: {:embed, Ecto.Embedded.init(cardinality: :one, field: :book)}
}

@keys Map.keys(@types) -- [:book]

@book_types %{
id: :integer,
name: :string
}

@book_keys Map.keys(@book_types)

def build(entity, attrs) do
entity
|> changeset(attrs)
|> apply_action(:validate)
end

def changeset(entity, attrs) do
{entity, @types}
|> cast(attrs, @keys)
|> cast_embed(:book, with: &book_changeset/2)
end

def book_changeset(entity, attrs) do
{entity, @book_types}
|> cast(attrs, @book_keys)
end
end

test "successfully casts schemaless embed" do
{:ok, data} = Author.build(%{}, %{name: "Jane", book: %{id: 1, name: "title 1"}})
assert %{name: "Jane", book: %{id: 1, name: "title 1"}} = data
end
end