Soft Delete with Discard

Episode #249 by Teacher's Avatar David Kimura

Summary

Soft deletes for ActiveRecord done right.
activerecord rails 6:53

Resources

Summary

# Terminal
rails g scaffold users first_name last_name email
rails g migration add_discard_to_users discarded_at:datetime:index
rails db:migrate
bundle add discard

# Gemfile
gem "discard", "~> 1.2"

# views/users/index.html.erb
<td><%= user.discarded? ? 'YES' : '' %></td>

# users_controller.rb
  before_action :set_user, only: [:show, :update, :destroy]

  def index
    # @users = User.kept
    @users = User.all
  end

  def edit
    @user = User.kept.find(params[:id])
  end

  def update
    # @user.discarded_at = nil if params.dig(:restore)
    @user.undiscard if params.dig(:restore)

    if @user.update(user_params)
      redirect_to @user, notice: 'User was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    if @user.discarded?
      @user.destroy
    else
      @user.discard
    end
    redirect_to users_url, notice: 'User was successfully destroyed.'
  end

# models/user.rb
class User < ApplicationRecord
  include Discard::Model
end

# views/users/_form.html.erb
  <%= content_tag :div, class: 'field' do %>
    <%= check_box_tag :restore %>
    Restore Deleted Record
  <% end if user.discarded? %>