Skip to content

Instantly share code, notes, and snippets.

@jeffreybaird
Last active June 22, 2016 18:29
Show Gist options
  • Save jeffreybaird/d11ccea1670ff1f1c77b to your computer and use it in GitHub Desktop.
Save jeffreybaird/d11ccea1670ff1f1c77b to your computer and use it in GitHub Desktop.
Question about the phoenix.gen.json generator.
$mix phoenix.new testapi
$cd testapi
$mix ecto.create
$mix phoenix.gen.json User users fullname:string email:string

Add the resource to your api scope in web/router.ex:

resources "/users", UserController, except: [:new, :edit]

under the api block

$mix ecto.migrate
$iex -S mix phoenix.server

In another terminal window:

$curl -H "Content-Type: application/json" -X POST -d '{"user": [{"fullname": "Jeff", "email": "[email protected]"}]}'   http://localhost:4000/api/users

Then I get this error in the iex window:

iex(1)> Processing by Testapi.UserController.create/2
  Parameters: %{"user" => [%{"email" => "[email protected]", "fullname" => "Jeff"}]}
  Pipelines: [:api]
[info] Sent 500 in 16ms
[error] #PID<0.405.0> running Testapi.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /api/users
** (exit) an exception was raised:
  ** (FunctionClauseError) no function clause matching in Ecto.Changeset.cast/5
    (ecto) lib/ecto/changeset.ex:351: Ecto.Changeset.cast(%Testapi.User{__meta__: #Ecto.Schema.Metadata<:built>, email: nil, fullname: nil, id: nil, inserted_at: nil, updated_at: nil}, %{}, [%{"email" => "[email protected]", "fullname" => "Jeff"}], ["fullname", "email"], [])
    (testapi) web/controllers/user_controller.ex:14: Testapi.UserController.create/2
    (testapi) web/controllers/user_controller.ex:1: Testapi.UserController.action/2
    (testapi) web/controllers/user_controller.ex:1: Testapi.UserController.phoenix_controller_pipeline/2
    (testapi) lib/phoenix/router.ex:255: Testapi.Router.dispatch/2
    (testapi) web/router.ex:1: Testapi.Router.do_call/2
    (testapi) lib/testapi/endpoint.ex:1: Testapi.Endpoint.phoenix_pipeline/1
    (testapi) lib/plug/debugger.ex:90: Testapi.Endpoint."call (overridable 3)"/2
    (testapi) lib/phoenix/endpoint/render_errors.ex:34: Testapi.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

I think this should result in a successful post. What am I missing?

@TimFerrell
Copy link

This was very useful to find. Thanks for the follow up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment