Search code examples
elixirphoenix-frameworkecto

In a Phoenix Framework form, how can I set a belongs_to relation back to null using a changeset?


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?


Solution

  • 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.