Building a Controller

You’ve already built a simple controller, so you know the drill. At this point, we could create all of the routes needed by a user automatically with the resources macro, but we are going to play the teacher and say “Show your work!” If you understand how a single route works, it’ll be much easier to explore the powerful shortcuts later. Specifically, we need two routes. UserController.index will show a list of users, and UserController.show will show a single user. As always, create the routes in router.ex:

 scope ​"​​/"​, RumblWeb ​do
  pipe_through ​:browser
 
  get ​"​​/users"​, UserController, ​:index
  get ​"​​/users/:id"​, UserController, ​:show
  get ​"​​/"​, PageController, ​:index
 end

Notice that we have our two new routes and the default route for /. Our two new routes use the new UserController, which doesn’t yet exist, with the :show and :index actions. The names and URLs we’ve chosen for these actions aren’t random. The :show, :index, :new, :create, :edit, :update, and :delete actions are all frequently used in Phoenix. For now, follow along strictly, and you’ll learn the shortcuts later.

Let’s take a closer look at the :index route:

 get ​"​​/users"​, UserController, ​:index

You’ve seen the get macro before. The route matches HTTP GET requests to a URL that looks like /users and sends them to the UserController, calling the index action. That route stores :index—the action we intend to invoke—in the conn and then calls the right pipeline.

Now, restart your server and point your browser to http://localhost:4000/users. You get some debugging information, but you don’t have to go beyond the title to find this message:

 UndefinedFunctionError at GET /users
 
 function RumblWeb.UserController.init/1 is undefined
 (module RumblWeb.UserController is not available)

That makes sense; we haven’t written the controller yet.

Let’s create a controller in lib/rumbl_web/controllers/user_controller.ex. Initially, we’ll include one function called index to find the users from our Accounts context:

 defmodule​ RumblWeb.UserController ​do
 use​ RumblWeb, ​:controller
 
  alias Rumbl.Accounts
 
 def​ index(conn, _params) ​do
  users = Accounts.list_users()
  render(conn, ​"​​index.html"​, ​users:​ users)
 end
 end

Let’s take that code apart. There’s a little bit of ceremony at the top of the file that defines our module and announces that we’re going to use the :controller API. Right now, the only action is index.

If you access the users page again, you can see that we’re getting an error message, but we’ve traded up:

 UndefinedFunctionError at GET /users
 
 undefined function: RumblWeb.UserView.render/2
  (module RumblWeb.UserView is not available)

Progress! We have a controller, but we still need to code a view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.136