In a Phoenix Framework form, I have a select box on my page which has an option to set a belongs_to value to nil.
<%= select f, :relation_id,
Enum.into(Enum.map(@relations, fn p -> {p.name, p.id} end),
[{"None", nil}]) %>
The form would usually send the ID, but when the nil value is selected, it passes the value as an empty string:
"relation_id" => ""
I receive an error from Ecto that the changeset is invalid, as it expects an integer. I could probably intercept the map, set the value to null, and pass the updated map into the changeset. But is there an easier way to do this?
I think you should use the plug scrub params.
Try to add to your controller:
defmodule MyApp.SomeThingController do
use MyApp.Web, :controller
plug :scrub_params, "some_thing" when action in [:create, :update]
# def ....
end
It will be convert ""
(empty) values to nil
values.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With