ardhitama
ardhitama

Reputation: 1982

Phoenix framework router.ex config for JSON

I've installed phoenix JSON package through mix phoenix.gen.json V1.Post posts title:string content:string secret:string --no-model but got this error:

== Compilation error on file web/controllers/v1/post_controller.ex ==
** (CompileError) web/controllers/v1/post_controller.ex:14: Shopper.V1.Post.__struct__/0 is undefined, cannot expand struct Shopper.V1.Post
(elixir) src/elixir_map.erl:55: :elixir_map.translate_struct/4
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(elixir) src/elixir_clauses.erl:36: :elixir_clauses.clause/7
(elixir) src/elixir_def.erl:178: :elixir_def.translate_clause/7
(elixir) src/elixir_def.erl:167: :elixir_def.translate_definition/8
(elixir) src/elixir_def.erl:82: :elixir_def.store_definition/9
web/controllers/v1/post_controller.ex:13: (module)
(stdlib) erl_eval.erl:669: :erl_eval.do_apply/6

here is my router.ex code:

defmodule Shopper.Router do
use Shopper.Web, :router

pipeline :api do
    plug :accepts, ["json"]
end

scope "/", Shopper do
    pipe_through :api
    resources "/v1/posts", V1.PostController
end
end

From the documentation said:

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

resources "/posts", PostController

But.. I can't make it work, could anybody help me? Thank you.

Please note that this is for phoenix 1.0 and elixir 1.0.

Upvotes: 1

Views: 492

Answers (1)

ardhitama
ardhitama

Reputation: 1982

My question is pointing to wrong problem, but I'll keep it that way so it can help people who coming with similar conclusion.

The solution is to add a model for V1.Post but running mix phoenix.gen.model will give a compile error which already stated in my question. So, I must comment the offending code which is the entire def create(conn, %{"post" => post_params}) in V1.Post controller.

After that run mix phoenix.gen.model V1.Post posts name:string then uncomment the offending code.

To test, run mix phoenix.routes which in my case returning

Compiled web/models/v1/post.ex
Generated shopper app
page_path  GET     /                  Shopper.PageController :index
post_path  GET     /api/v1/posts      Shopper.V1.PostController :index
post_path  GET     /api/v1/posts/:id  Shopper.V1.PostController :show
post_path  POST    /api/v1/posts      Shopper.V1.PostController :create
post_path  PATCH   /api/v1/posts/:id  Shopper.V1.PostController :update
           PUT     /api/v1/posts/:id  Shopper.V1.PostController :update
post_path  DELETE  /api/v1/posts/:id  Shopper.V1.PostController :delete

Success!

Upvotes: 0

Related Questions