kansiho's memo

ruby, python, javascript. Rails, wordpress, OpenCV, heroku...

Deviseで管理者が承認したらユーザーのアカウントをアクティベートする実装【Rails】

f:id:serendipity4u:20170417172047p:plain

userカラムにapprovedを足す

class AddApprovedToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :approved, :boolean, :default => false, :null => false
    add_index  :users, :approved
  end

  def self.down
    remove_index  :users, :approved
    remove_column :users, :approved
  end
end

userモデルをオーバーライドする

def active_for_authentication? 
    super && approved? 
  end 

  def inactive_message 
    if !approved? 
      :not_approved 
    else 
      super # Use whatever other message 
    end 
  end

利用承認待ちだというメールを自動送信

  after_create :send_admin_mail
  def send_admin_mail
    AdminMailer.new_user_waiting_for_approval(self).deliver
  end

view も作る。

path を指定

def after_sign_up_path_for(resource)
  after_sign_in_path_for(resource)
end


def after_inactive_sign_up_path_for(resource)
  welcome_index_path
end

環境に応じて改変する

参考

How To: Require admin to activate account before sign_in · plataformatec/devise Wiki · GitHub

How To: redirect to a specific page on successful sign_in, sign_out, and or sign_up · plataformatec/devise Wiki · GitHub