I’m having a few problems with Ecto’s embeds_many
feature:
-
scrub_params
nils out empty forms but doesn’t remove them… - What is the idiomatic way of removing empty nested forms?
Conn Params params["inventories"]
:
%{"payment_invoice_type" => "mail",
"shipping_methods" =>
%{"0" => %{"cost" => "10.00", "description" => "Del Option 1"},
"1" => %{"cost" => "20.00", "description" => "Del Option 2"},
"2" => %{"cost" => "30.00", "description" => "Del Option 3"},
"3" => %{"cost" => nil, "description" => nil}, # should be discarded
"4" => %{"cost" => nil, "description" => nil}}, # should be discarded
"payment_method" => "cash",
}
Changeset results:
#Ecto.Changeset<action: nil,
changes: %{payment_invoice_type: "mail,
delivery_methods: [#Ecto.Changeset<action: :insert,
changes: %{cost: #Decimal<10.00>, description: "Del Option 1"}, errors: [],
data: #Book.Store.ShippingMethod<>, valid?: true>,
#Ecto.Changeset<action: :insert,
changes: %{cost: #Decimal<20.00>, description: "Del Option 2"}, errors: [],
data: #Book.Store.ShippingMethod<>, valid?: true>,
#Ecto.Changeset<action: :insert,
changes: %{cost: #Decimal<30.00>, description: "Del Option 3"}, errors: [],
data: #Book.Store.ShippingMethod<>, valid?: true>,
#Ecto.Changeset<action: :insert, changes: %{},
errors: [description: {"can't be blank", [validation: :required]},
cost: {"can't be blank", [validation: :required]}],
data: #Book.Store.ShippingMethod<>, valid?: false>,
#Ecto.Changeset<action: :insert, changes: %{},
errors: [description: {"can't be blank", [validation: :required]},
cost: {"can't be blank", [validation: :required]}],
data: #Book.Store.ShippingMethod<>, valid?: false>],
payment_method: "cash"},
errors: [],
data: #Book.Store.Inventory<>, valid?: false>
Parent Schema:
schema "inventories" do
field :payment_invoice_type, :string
field :payment_method, :string
embeds_many :shipping_methods, Book.Store.ShippingMethod
timestamps()
end
Parent Changeset:
def changeset(%Inventory{} = inventory, attrs) do
inventory
|> cast(attrs, [:payment_invoice_type, :payment_method])
|> validate_required([:payment_invoice_type, :payment_method])
|> cast_embed(:shipping_methods, required: true)
end
Embedded Schema:
@primary_key false
embedded_schema do
field :description, :string
field :cost, :decimal
end
def changeset(%DeliveryMethod{} = delivery_method, attrs) do
delivery_method
|> cast(attrs, [:description, :cost])
|> validate_required([:description, :cost])
|> validate_length(:description, min: 5, max: 75)
end