Deleting a Post

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

Delete Post Route

For our delete route, we will be using the DELETE http verb.

# /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
  get "/posts/:id/edit", PostsController, :edit, as: :post
  put "/posts/:id", PostsController, :update, as: :post
  delete "/posts/:id", PostsController, :delete, as: :post
end

Delete Post Controller Endpoint

In our controller we will be finding the Post by its id and then using the Repo to delete the record.

# /web/controllers/posts_controller.ex
defmodule Readdit.PostsController do
  ...
  def delete(conn, %{ "id" => id }) do
    post = Readdit.Post 
    |> Readdit.Repo.get(id)
    |> Readdit.Repo.delete!

    conn |> redirect(to: posts_path(conn, :index))
  end
  ...
end

Add the Delete link

In our Post’s show page, we will add a Delete link. Notice we changed the method used by this link with method: :delete. Just like Rails behind the scenes Phoenix is replacing this link with a form and then adds special fields that Phoenix’s uses when routing the form submission.

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

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

<%= link to: post_path(@conn, :edit, @post) do %>
 Edit
<% end %>

<%= link "Delete", to: post_path(@conn, :delete, @post), method: :delete %>

<p>
  <%= @post.content %>
</p>

Delete a post

  1. From http://localhost:4000/posts click on a Post’s title link.
  2. On the post’s page we now see our Delete link.
  3. Click the Delete link.
  4. We should be redirected back to our /posts page and our post should now be deleted.