Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
Don Pflaster Avatar asked Feb 03 '16 16:02

Don Pflaster


1 Answers

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.

like image 119
Fabi755 Avatar answered Oct 23 '22 11:10

Fabi755