0
1

More than 3 years have passed since last update.

deviseでメールアドレスとパスワード以外をDBに保存する方法

Posted at

ユーザーの名前をDBに保存する方法

deviseではDBに保存できるカラムが決まっています。なので他のカラム情報をDBに保存する際は、ストロングパラメーターの設定が必要です。
設定はapp/controllers/application_controller.rbに記述します。
※deviseのコントローラーの処理を記述する時は、application_controller.rbに記述すると良いです。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  private
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end

上記のように記述します。
まず、

app/controllers/application_controller.rb
before_action :configure_permitted_parameters, if: :devise_controller?

この一文ですが、deviseのコントローラーから呼び出されたかどうかを記述しています。

app/controllers/application_controller.rb
private
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end

そして、deviseのコントローラーから呼び出された場合、ユーザーの名前もDBに保存することを許可しています。
ちなみにconfigure_permitted_parametersは慣習的な記述なので自由に決めても問題ありません。

今回は、name・・・つまりユーザー名をDBに保存する許可をしましたが、age・・・年齢、birthplace・・・出身とか必要な許可をしてあげることが出来ます。

0
1
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
0
1