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

In the Phoenix Framework form, I have a selection box on my page that has the option to set the own_to value to nil.

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

The form usually sends an identifier, but when nil is selected, it passes the value as an empty string:

 "relation_id" => "" 

I get an Ecto error message that the change set is invalid because it expects an integer. Perhaps I could intercept the map, set it to null, and pass the updated map to the changeset. But is there an easier way to do this?

+5
source share
1 answer

I think you should use scrub options.

Try adding to the controller:

 defmodule MyApp.SomeThingController do use MyApp.Web, :controller plug :scrub_params, "some_thing" when action in [:create, :update] # def .... end 

It converts the "" (empty) values ​​to nil values.

Hope this helps.

+5
source

Source: https://habr.com/ru/post/1242220/


All Articles