23
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】論理削除(退会機能)

Last updated at Posted at 2020-10-26

目標

画面収録 2020-10-25 21.31.39.mov.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

流れ

1 カラムの追加
2 modelの編集
3 controllerの編集

カラムの追加

ターミナル
$ rails g migration AddIsValidToUsers is_valid:boolean

default: true, null: falseを追加。
booleanを使用することにより、ture、falseで退会しているかどうかを判断します。
下記の場合は初期値をtrueに設定しますので、退会済みの場合はfalseとなります。

db/migrate/xxxxxxxxxxxxx_add_is_valid_to_users.rb
class AddIsValidToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :is_valid, :boolean, default: true, null: false
  end
end
ターミナル
$ rails db:migrate

controllerの編集

退会画面と退会処理のアクションを作成

app/controllers/homes_controller.rb
  def unsubscribe
    @user = User.find_by(name: params[:name])
  end

  def withdraw
    @user = User.find_by(name: params[:name])
    @user.update(is_valid: false)
    reset_session
    redirect_to root_path
  end

退会後のログインを阻止する記述。

app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  before_action :reject_inactive_user, only: [:create]

...

  def reject_inactive_user
    @user = User.find_by(name: params[:user][:name])
    if @user
      if @user.valid_password?(params[:user][:password]) && !@user.is_valid
        redirect_to new_user_session_path
      end
    end
  end
end

routesの編集

config/routes.rb
get 'unsubscribe/:name' => 'homes#unsubscribe', as: 'confirm_unsubscribe'
patch ':id/withdraw/:name' => 'homes#withdraw', as: 'withdraw_user'
put 'withdraw/:name' => 'users#withdraw'

viewの編集

app/views/homes/unsubscribe.html.erb
<div>
  <h2>本当に退会しますか?</h2>
  <div>
    <p>退会する場合は、『退会する』をクリックしてください。</p>
  </div>
  <div>
    <%= link_to '退会しない', mypage_path(@user) %>
    <%= link_to "退会する", withdraw_user_path(@user), method: :patch %>
  </div>
</div>

参考

PUT か POST か PATCH か?

まとめ

論理削除のメリット、デメリットは色々あると思いますが、
サービスを運営する場合、顧客情報は大切になりますので、
物理削除ではなく、論理削除で退会にしたほうが、
復活の手段にもなるためおすすめです。

またtwitterではQiitaにはアップしていない技術や考え方もアップしていますので、
よければフォローして頂けると嬉しいです。
詳しくはこちら https://twitter.com/japwork

23
39
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?