Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horribly redundant Phoenix controller

I'm doing my first Phoenix application, and trying to do 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 horribly redundant and I can't find any better way to do this. I've read that there is no way to convert Map to Struct, and since the params differ in type it wouldn't work anyway.

So can anybody show me some magic way to map it?

like image 453
Krzysztof Wende Avatar asked Sep 28 '22 17:09

Krzysztof Wende


1 Answers

Please look into Ecto changesets as they do casting based on your model information. They are going to take care of all the parsing, validation and more.

My advice is to use one of mix phoenix.gen.html or mix phoenix.gen.json to generate some sample structure so you learn quickly how all the pieces fit together:

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

Note thought the generator will conflict with your code above if you have already defined a Chat model.

like image 200
José Valim Avatar answered Oct 31 '22 16:10

José Valim