Phoenix Framework – Setting an associated ID back to nil using a form

When using a Phoenix Framework form, I had a select box on my page which had an option to set a belongs_to value to nil.

<%= select f, :relation_id, 
  Enum.into(, fn p -> {,} end),
[{"None", nil}]) %>

The form would usually send the ID, but when the nil value is selected, it passed the value as an empty string:

"relation_id" => ""

When I pass this into an Ecto changeset, it throws an error that the changeset is invalid, as it expects an integer for this ID. I could probably have intercepted the map, set the value to null, and passed the updated map into the changeset. But there was a much easier way to do this.

In the controller that receives the params, throw in the following plug which will strip params that are empty strings and convert them to nils:

defmodule MyApp.SomeThingController do
use MyApp.Web, :controller

plug :scrub_params, "some_thing" when action in [:create, :update]

# def ....

Where “some_thing” is the object in your params that has the “relation_id” field. Thanks to Stack Overflow!

Posted in Ecto, Elixir, Phoenix

Leave a Reply

Your email address will not be published. Required fields are marked *