Josh
Josh

Reputation: 3090

Controller undefined after generation

Just started using Phoenix and I generated the project and ran phoenix.gen.json Todo todos description:string

/lib/test_web/router.ex

# Other scopes may use custom stacks.
      scope "/api", TestWeb do
        pipe_through :api

        resources "/todos", TodoController, except: [:new, :edit]
      end

/web/controllers/todo_controller.ex

defmodule Test.TodoController do
  use Test.Web, :controller

  alias Test.Todo

  def index(conn, _params) do
    todos = Repo.all(Todo)
    render(conn, "index.json", todos: todos)
  end
end

And a GET to /api/todos gives a 500 - ** (UndefinedFunctionError) function TestWeb.TodoController.init/1 is undefined (module TestWeb.TodoController is not available)

Upvotes: 0

Views: 1930

Answers (2)

Josh
Josh

Reputation: 3090

Use the same modern version of the generator (phx.gen.json). Old generator was defining modules outside the scope of the project.

Working after switching to the new generator.

Upvotes: 0

Brett Beatty
Brett Beatty

Reputation: 5963

Your router and your controller are expecting two different parent modules for your controller. You have the router looking for the controller under 'TestWeb' (see the scope), but your controller says it's 'Test.TestController' not 'TestWeb.TestController'.

One solution would be to change scope "/api", TestWeb do to scope "/api", Test do.

Another option would be to change defmodule Test.TodoController do to defmodule TestWeb.TodoController do.

It's really a matter of preference (though sticking to the generator's convention might be nice).

Upvotes: 2

Related Questions