Deviseでパスワードなしで設定変更する方法

f:id:ihatov08:20160809101914j:plain
Deviseでパスワードなしで設定変更する方法です。

パスワードなしで設定変更可能にする

deviseのwikiにやり方が書いてました。

How To: Allow users to edit their account without providing a password · plataformatec/devise Wiki · GitHub

設定変更をするregistrations_controllerにメソッドを定義します。deviseで定義されているupdate_without_passwordメソッドを用いる形ですね。

class RegitrationsController < Devise::RegistrationsController
protected
def update_resource(resource, params)
resource.update_without_password(params)
end

ルーティングも変更します。

devise_for :users, controllers: {registrations: 'registrations'}

パスワードも変更可能にする

しかし、上記実装だとpasswordが更新できません。
passwordのparamsを送るだけでpasswordを変更可能な実装にしたいと思います。password_confirmationが不要でpassword更新可能にします。

そんなときは対象のmodelでupdate_with_passwordメソッドをオーバーライドします。

def update_with_password(params, * options)
if params[:password].blank?
params.delete(:password)
params.delete(:password_confirmation) if params[:password_confirmation].blank?
end
update_attributes(params, * options)
end

オーバーライドしたメソッドをcontrollerで使えば、passwordのparamsが送られたときだけ,passwordが更新されます。

registrations_controller.rb

def update
resource.update_with_password(account_update_params)
....
protected
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [ :agreement, :profile, :sex, :telephone_number])
end

configure_account_update_paramsは実際にparamsとして使うときはaccount_update_paramsで使うみたいです。でバックしてみたら、configureを先頭につけたらnilが返ってきました。

Ruby on Rails 4 アプリケーションプログラミング

Ruby on Rails 4 アプリケーションプログラミング

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です