5

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?

Krzysztof Wende
  • 3,208
  • 25
  • 38

2 Answers2

5

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.

José Valim
  • 50,409
  • 12
  • 130
  • 115
  • So there is no pure code solution? I don't like code generating commands. It's cheating ;) – Krzysztof Wende Jun 03 '15 at 21:59
  • 3
    The generator is not there to generate your whole application, it is there as a learning tool to show you how to structure your code. You don't need to use it at the end of the day, but take a look at what is generated at least once to learn the concepts required to build CRUD in Phoenix. – José Valim Jun 04 '15 at 09:29
  • After generating I'm getting 12 out of 14 tests failing because Project.ErrorView.render/2 is undefined. Should I generate it too somehow or write by hand? – Krzysztof Wende Jun 04 '15 at 19:33
  • If you created your Phoenix application with mix phoenix.new, the ErrorView should be automatically generated. – José Valim Jun 04 '15 at 21:00
  • Maybe I deleted that by mistake. Thanks again :) – Krzysztof Wende Jun 04 '15 at 23:05
-1

The struct function will convert a map to a struct:

iex(3)> defmodule User do         
...(3)> defstruct name: "john"    
...(3)> end

iex(4)> struct(User, %{name: "foo"})
%User{name: "foo"}
Gazler
  • 83,029
  • 18
  • 279
  • 245