What was the reason for changing mix phx.gen.schema generated changeset function?

I’m writing down an example from Phoenix inside out by @shankardevy.

In earlier versions of Phoenix if we ran mix phx.gen.schema Sales.Order orders status:string total:decimal line_items:array:map the resulted order.ex file was something like the following,

defmodule Mango.Sales.Order do
  use Ecto.Schema
  import Ecto.Changeset
  alias Mango.Sales.Order


  schema "orders" do
    field :line_items, {:array, :map}
    field :status, :string
    field :total, :decimal

    timestamps()
  end

  @doc false
  def changeset(%Order{} = order, attrs) do
    order
    |> cast(attrs, [:status, :total, :line_items])
    |> validate_required([:status, :total, :line_items])
  end
end

Somewhere in 1.3.X this behavior changed a little bit, now it will generate the following order.ex file.

defmodule Mango.Sales.Order do
  use Ecto.Schema
  import Ecto.Changeset


  schema "orders" do
    field :line_items, {:array, :map}
    field :status, :string
    field :total, :decimal

    timestamps()
  end

  @doc false
  def changeset(order, attrs) do
    order
    |> cast(attrs, [:status, :total, :line_items])
    |> validate_required([:status, :total, :line_items])
  end
end

(removing alias Mango.Sales.Order and the match of first argument against %Order{})

What was the reason for this change?

@chrismccord @josevalim @ericmj @Gazler @jeregrine @lance @scrogson

Was this because matching against the struct (%Order{} in this example) was unnecessary? Or matching against the struct was causing some problem?

Both examples are fine. We probably changed it to keep it simpler but it is ok to add the pattern matching if you prefer to make it strict.

1 Like

I tend to leave off the pattern match as sometimes I already have an Ecto.Changeset to be used as the first argument. This makes composing multiple functions working on a changeset simpler and easier to refactor.

1 Like