luzny
luzny

Reputation: 2400

Where and How to wrap params before changeset validation?

Next difficulty after previous question, I'm trying to pass into changeset coordinates wrapped by %Geo.Point function, in Map.put coordinates key stay immutable, but target question is How and where should coordinates be wrapped? Can I do this somewhere inside pattern maching or maybe better before pass changeset in controller or in changeset method in model?

def create(conn, %{"notify" => %{"coordinates" => %{"latitude" => latitude, "longitude" => longitude}} = notify_params}) do
  geo = %Geo.Point{coordinates: {latitude, longitude}}
  Map.put(notify_params, :coordinates, geo ) # coordinates are immutable
  changeset = Notify.changeset(%Notify{}, notify_params)
  #...
end

Upvotes: 3

Views: 94

Answers (1)

Gazler
Gazler

Reputation: 84140

Using Map.put(notify_params, :coordinates, geo) will work, however you are not binding the value.

This will rebind the notify_params variable with your new value. Please note that you should use "coordinates" instead of :coordinates as the params use strings as keys.

notify_params = Map.put(notify_params, "coordinates", geo)

There is another (preferred) syntax for map updates that will error if the key does not exist.

notify_params = %{notify_params | "coordinates" => geo}

Upvotes: 4

Related Questions