Lesson 6

Building a Detail Page

In this lesson we will add a detail page to display a single quote. We will do this in the quote controller and the show action.

We want to link to the detail page from the index page. Add the link in the web/templates/quote/index.html.eex file:

<table>
  <thead>
    <tr>
      <th>Saying</th>
      <th>Author</th>
  </thead>
  <%= for q <- @quotes do %>
  <tr>
    <td>
<a href="<%=quote_path(@conn, :show, q.id) %>"> <%= q.saying %> </a>
</td> <td> <%= q.author %> </td> </tr> <% end %> </table>

Save the file. Navigate to localhost:4000/quotes and you will see the saying is now a link that will send the user to the detail page.

When you click the link you will see an error that indicates that we haven't built the show action in the quote controller yet.

Edit web/controllers/quote_controller.ex to include the show action by adding the following method:

defmodule Splurty.QuoteController do
  use Phoenix.Controller

  alias Splurty.Router
  import Splurty.Router.Helpers

  plug :action

  def homepage(conn, _params) do
    render conn, "homepage.html"
  end

  def index(conn, _params) do
    conn
    |> assign(:quotes, Repo.all(Splurty.Quote))
    |> render("index.html")
  end

  def new(conn, _params) do
    render conn, "new.html"
  end

  def create(conn, %{"quote" => %{"saying" => saying, "author" => author}}) do
    q = %Splurty.Quote{saying: saying,  author: author}
    Repo.insert(q)

    redirect conn, to: quote_path(conn, :index)
  end

def show(conn, %{"id" => id}) do {id, _} = Integer.parse(id) conn |> assign(:quote, Repo.get(Splurty.Quote, id)) |> render("show.html") end
end

Save the file.

The first thing this does is convert the id we extract from the parameters in the URL from a string to an integer. If we don't do this, Ecto will give us error messages about type errors.

This also renders the show.html template and assigns the quote we load up from the Repo with the proper id into the @quote assignment.

Refresh the page and you will see a different error message, which indicates we haven't build the template yet.

Add the template file web/templates/quote/show.html.eex with the following dummy content within it:

hi

Save the file and refresh the page. Excellent, the error goes away and are presented with the "hi" message.

Add the saying and the author as headers on web/templates/quote/show.html.eex like this:

<h1>
  <%= @quote.saying %>
</h1>

<h2>
  <%= @quote.author %>
</h2>

Save the file and refresh the page. Awesome, we now see the details of the quote presented to us on the quote detail page.

Your application should look just like this at this step.

Next Lesson