Deleting and Undeleting with Paranoia

Episode #19 by David Kimura

Summary

When your app is using Paranoia, calling destroy on an ActiveRecord object doesn't actually destroy the database record, but just hides it.
rails view model 7:34

Resources

Summary

# Gemfile
gem "paranoia"

# bash
rails g migration add_deleted_at_to_comments deleted_at:datetime:index

# comment.rb
    class Comment < ActiveRecord::Base
      acts_as_paranoid
    end

# bash
    rails db
    sqlite> .mode column
    sqlite> .headers on
    sqlite> select * from comments;

# console
    Comment.last.destroy
    Comment.with_deleted.last.restore
    Comment.last.really_destroy!

# show.html.erb
    <div class='col-xs-8'>
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Comments</h3>
        </div>
        <ul class='list-group'>
          <% @user.comments.each do |comment| %>
            <li class='list-group-item'>
              <%= comment.content %>
              <span class='pull-right'>
                <%= link_to 'delete', user_comment_path(@user, comment, type: :normal), method: :delete, class: 'badge' %>
                <em><%= time_ago_in_words comment.created_at %></em>
            </li>
          <% end %>
        </ul>
      </div>

      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Deleted Comments</h3>
        </div>
        <ul class='list-group'>
          <% @user.comments.only_deleted.each do |comment| %>
            <li class='list-group-item'>
              <%= comment.content %>
              <span class='pull-right'>
                <%= link_to 'undelete', user_comment_path(@user, comment, type: :undelete), method: :delete, class: 'badge' %>
                <%= link_to 'really delete', user_comment_path(@user, comment, type: :forever), method: :delete, class: 'badge' %>
                <em><%= time_ago_in_words comment.created_at %></em>
            </li>
          <% end %>
        </ul>
      </div>
    </div>

# users_controller.rb
    @user = User.find(params[:user_id])
    @comment = @user.comments.with_deleted.find(params[:id])
    if params[:type] == 'normal'
      @comment.destroy
    elsif params[:type] == 'forever'
      @comment.really_destroy!
    elsif params[:type] == 'undelete'
      @comment.restore
    end