Viewing a Post

Building an app with Phoenix : part 7 of 9 published on Aug 10, 2015

Show Post Route

Like before, we will start by adding the route.

# /web/router.ex

scope "/", Readdit do
 get "/posts", PostsController, :index
 get "/posts/new", PostsController, :new
 post "/posts", PostsController, :create
 get "/posts/:id", PostsController, :show, as: :post

We will then add a link in our index page

<!-- /web/templates/posts/index.html.eex -->

<a class="btn btn-default" href="/posts/new">New Post</a>

<%= for post <- @posts do %>
    <%= link to: post_path(@conn, :show, post) do %>
      <%= post.title %>
    <% end %>
    <%= post.content %>
<% end %>

Notice this time instead of using a string for the route, we used a named path (in our case post_path). The post_path was created when we added as: :post to our route.

Show Post Controller Endpoint

For our controller endpoint, we will expect the id passed in as a parameter from the route. We will use that id to find the Post we want to pass to the view.

# /web/controllers/post_controller.ex
  def show(conn, %{ "id" => id }) do
    post = Readdit.Post |> Readdit.Repo.get(id)
    render conn, "show.html", post: post

Show Post Template

For our show template, we will just display the title and content. We will add more to this template as we add more features to our app.

<!-- /web/templates/posts/show.html.eex -->
<a href="/posts">Back to posts</a>

<h1><%= @post.title %></h1>

  <%= @post.content %>

Checking out our new page

Now if we go to http://localhost:4000/posts we should see our list of posts and their titles should be links.

If we click the title link, we should then be sent to our Post show page.

Next: Editing a Post