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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With