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

Load virtual into schema struct #4586

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
1 change: 1 addition & 0 deletions lib/ecto/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2344,6 +2344,7 @@ defmodule Ecto.Schema do
{name, type}
end
end
|> Keyword.merge(virtual_fields)

dump =
for {name, {type, writable}} <- fields do
Expand Down
4 changes: 4 additions & 0 deletions test/ecto/embedded_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ defmodule Ecto.EmbeddedTest do

embedded_schema do
field :dark_mode, :boolean, default: false
field :n, :integer, virtual: true
embeds_one :default_post, Post, defaults_to_struct: true
end
end
Expand Down Expand Up @@ -78,6 +79,9 @@ defmodule Ecto.EmbeddedTest do
assert %Settings{dark_mode: false, default_post: nil} =
Ecto.embedded_load(Settings, %{"default_post" => nil}, :json)

assert %Settings{n: 1} =
Ecto.embedded_load(Settings, %{"n" => 1}, :json)

assert_raise ArgumentError,
~s[cannot load `"ABC"` as type Ecto.UUID for field `uuid` in schema Ecto.EmbeddedTest.UUIDSchema],
fn ->
Expand Down
5 changes: 5 additions & 0 deletions test/ecto/repo_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ defmodule Ecto.RepoTest do
field :y, :binary, source: :yyy
field :z, :string, default: "z"
field :w, :string, virtual: true
field :n, :integer, virtual: true
field :array, {:array, :string}
field :map, {:map, :string}
has_many :children, MySchemaChild
Expand Down Expand Up @@ -230,6 +231,10 @@ defmodule Ecto.RepoTest do
assert %MySchema{map: %{"color" => "red"}} =
TestRepo.load(MySchema, %{map: %{"color" => "red"}})

# virtual field
assert %MySchema{n: 1} =
TestRepo.load(MySchema, %{n: 1})

# nil
assert %MySchema{x: nil} =
TestRepo.load(MySchema, %{x: nil})
Expand Down