Deviseのユーザー登録時に、独自の処理を追加する。
2014年2月3日
Railsの認証処理にdeviseを用いている場合、新規ユーザーの登録は自動的に行われます。デフォルトではUsersテーブルに設定したemailとpasswordが保存されます。これはこれでOKなのですが、アプリケーションの仕様上、ユーザーを新規に追加したタイミングで別の処理を実行したいケースがあると思います。今回はそんなケースに対応する方法を説明します。
deviseのソースをチェックすると RegistrationsControllerの createメソッドで、ユーザーの登録処理が行われているようです。ですので、今回はこのメソッドをオーバーライドして、追加の処理も実行します。
DeviseのRegistrationsControllerを継承するクラスを定義する。
ファイルの場所は app/registrations_controller.rb とします。
[ruby mark=”15-16,29-31″]
class RegistrationsController < Devise::RegistrationsController
# POST /resource
def create
build_resource(sign_up_params)
if resource.save
yield resource if block_given?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
#独自の処理を追加
createXXXX(resource)
else
set_flash_message :notice, :”signed_up_but_#{resource.inactive_message}” if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
respond_with resource
end
end
def createXXXX(resource)
ここに追加の処理を記述
end
end
[/ruby]
routes.rbを調整し、新規ユーザー登録時に、上記のメソッドが呼ばれるようにする。
[diff]
– devise_for :users
+ devise_for :users, controllers: {registrations: “registrations”}
[/diff]
以上です。
Leave a comment