Skip to content

new_ functions do not play well with embeds #10

Description

@hqm42

Example:

# foos.ex
defmodule Foos do
  use ContextKit.CRUD,
    repo: MyRepo,
    schema: Foo,
    queries: __MODULE__
end

# foos/foo.ex

defmodule Foos.Foo do
  use Ecto.Schema

  import Ecto.Changeset

  schema "foos" do
    embeds_one :bar, Bars.Bar, on_replace: :delete
  end

  def changeset(foo, attrs) do
    foo
    |> cast(attrs, [])
    |> cast_embeded(:bar)
  end
end
iex(localportal@localhost)1> Foos.new_foo
** (RuntimeError) casting embeds with cast/4 for :bar field is not supported, use cast_embed/3 instead

Why isn't new_ implemented as follows?

        @spec unquote(:"new_#{resource_name}")(params :: map(), opts :: keyword()) :: unquote(schema).t()
        def unquote(:"new_#{resource_name}")(params, opts) when is_map(params) and is_list(opts) do
          record =
            unquote(schema).__struct__()
            |> unquote(schema).changeset(params)
            |> Ecto.Changeset.apply_changes()

          if opts[:preload], do: unquote(repo).preload(record, opts[:preload]), else: record
        end

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions