0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

deviseを導入したが更にカラムを増やしたい時

Last updated at Posted at 2020-05-19

deviseを使ってみて

deviseを導入したがカラムこれだけって時ありませんか?

今回はカラムの追加方法について説明します!!

#1.usersテーブルにカラムを追加します

今回はnameカラムを追加します。
ターミナルで以下のコマンドを実行しましょう。

$ rails g migration AddNameToUsers name:string

$ rails db:migrate

#2.application_controller.rbを編集

application_controller.rbを以下のように編集しましょう。
これでユーザー登録時にnameカラムが保存されるようになりました。

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

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

※今のままでは登録時にしかnameカラムが入っていないので、編集でnameを変更しても変更されません。

3.編集時に追加したカラムの編集もできるようにしましょう!

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

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    <!-- 以下のように編集時の対応する記述も追加してあげましょう -->
    devise_parameter_sanitizer.permit(:account_update, keys: [:name])
  end
end

これで編集時にデータが反映される様になりました:point_up_tone2:

この記事が少しでも参考になれば嬉しいです:pray_tone2:

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?