5
votes

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?

1
How do you preload the relations field in your controller? Can't find an example on how to do it with a changeset. ThanksPaco
Ahh - the select just expects a basic list of tuples and can be generated however you like. In this case, @relations was just a straight pull using Repo.all: relations = Repo.all(relations_query), and then passed into the view in the render command.Don Pflaster

1 Answers

5
votes

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.