Terribly Redundant Phoenix Controller

I am making my first Phoenix app and am trying to make a new / 2 controller. The code I wrote is

def new(conn, %{"fbid" => fbid, "latitude" => lat, "longitude" => lng, "content" => content}) do {fbid, _} = Integer.parse(fbid); {lat, _} = Float.parse(lat); {lng, _} = Float.parse(lng); chats = %Chat{:fbid => fbid, :latitude => lat, :longitude => lng, :content => content} |> Repo.insert |> List.wrap |> Poison.encode! render conn, chats: chats end 

But it looks terribly redundant, and I cannot find a better way to do this. I read that there is no way to convert Map to Struct, and since the parameters are different in type, it still won't work.

So can someone show me some magical way to display it?

+5
source share
2 answers

Take a look at Ecto changesets as they cast based on your model information. They are going to take care of all parsing, validation and more.

My advice is to use one of mix phoenix.gen.html or mix phoenix.gen.json to create some sort of sampling structure so that you quickly find out how all the parts match:

 mix phoenix.gen.html Chat chats fbid:integer latitude:float longitude:float content:string 

Please note that the generator will conflict with your code above if you have already defined the Chat model.

+5
source

The struct function converts a map into a structure:

 iex(3)> defmodule User do ...(3)> defstruct name: "john" ...(3)> end iex(4)> struct(User, %{name: "foo"}) %User{name: "foo"} 
-1
source

All Articles