How to Create the Ability to Delete Posts in Rails
In this guide, we are going to build our delete functionality.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide, we are going to build our delete functionality.

As you may have guessed, we're going to start with a test case in our post_spec.rb file.

The delete functionality is more complex than it may look because of the workflow of the system. For example, we need to build in the ability for an employee to delete a record if he or she thinks there's a mistake in it. However, it cannot be deleted after an approver or manager approves the record because it has to be present for audit purposes.

For now, we're not going to worry about all of these complexities, we'll simply build in the basic delete functionality.

# spec/features/post_spec.rb

describe 'delete' do
  it 'can be deleted' do
    @post = FactoryGirl.create(:post)
    visit posts_path

    click_link("delete_post_#{@post.id}_from_index")
    expect(page.status_code).to eq(200)
  end
end

Like previous test cases, this one will create a post, visit it, click on a link called delete and expect that page to be present. This won't actually test the full delete functionality, it will simply ensure that the link exists and that there aren't any errors.

Again, rspec will fail because it's unable to find the link. To fix this, go to_post.html.erb and include a "Delete" link next to "Edit" link with the following code:

<!-- app/views/posts/_post.html.erb -->

<td>
  <%= link_to 'Delete', post_path(post), method: :delete, id: "delete_post_#{post.id}_from_index", data: { confirm: 'Are you sure?' } %>
</td>

If you run rspec now, it'll say there is no destroy action in the PostsController. So, to fix that, let's open posts_controller.rb and add the following code in it.

# app/controllers/posts_controller.rb

def destroy
  @post.delete
  redirect_to posts_path, notice: 'Your post was deleted successfully'
end

In this code, we are deleting a post and redirecting the user to the posts page along with a message.

Now, if you run rspec, everything will be passing.

One thing that I'd like to point out here is the pattern. Over the last videos, we are redirecting to a specific page after an action is completed. This is because, by default, Rails looks for a view file with the same name as the action. So, if you don't redirect, rails will look for a file called delete.html.erb. This is why we are having a redirect command at the end of every action.

Now let's see it in a browser.

large

It looks and works fine.

Resources