4
5

More than 5 years have passed since last update.

[Devise] Rails4 の StrongParameter をDeviseのControllerにも適応させる方法

Last updated at Posted at 2015-01-11

はじめに

基本的に大体のことは 本家のDocument(wiki) をみれば書いてあるので、まずはそちらに目を通すといい。

Defaultでの設定

documentを見ると、それぞれのControllerで違いますが、概ねauthentication keysが設定されていて、passwordとpassword_confirmation、current_passwordも対象になっている様です。

sign_in:  (Devise::SessionsController#create)
Permits only the authentication keys (like email)
sign_up:  (Devise::RegistrationsController#create)
Permits authentication keys plus password and password_confirmation
account_update:  (Devise::RegistrationsController#update)
Permits authentication keys plus password, password_confirmation and current_password

ApplicationControllerで一気に追加

sign_up(Devise::RegistrationsController)に対して、usernameをStrongParameterに追加するメソッドを追加。
ApplicationControllerが読み込まれる際に、controllerを見て、devise_controllerであれば、strongParameterの追加を実行。

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :username
  end
end

書き換える場合

こんな感じです。

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
end

複数のDeviseモデルを使う場合

Sanitizerを使う場合

とりあえず対象のクラスにSanitizerを書いておきます。

class User::ParameterSanitizer < Devise::ParameterSanitizer
  def sign_in
    default_params.permit(:username, :email)
  end
end

あとはそれを必要なところに読み込ませたらいい感じです。

applicationcontrollerなら

class ApplicationController < ActionController::Base
  protected

  def devise_parameter_sanitizer
    if resource_class == User
      User::ParameterSanitizer.new(User, :user, params)
    else
      super # Use the default one
    end
  end
end

対象のControllerに処理をまとめたい場合

class Users::RegistrationsController < Devise::RegistrationsController
  def sign_up_params
     devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :name, :password, :password_confirmation) }
     super
  end
end

validation

モデルにちゃんとvalidationを記述するのを忘れずに。

References

4
5
0

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
4
5