LoginSignup
0
1

More than 5 years have passed since last update.

【rails5】特定のアクションでのみパスワード再確認を実施する方法

Last updated at Posted at 2019-01-28

特定のアクションでのみパスワード再確認を実施する方法

ユーザーの新規登録時には、パスワードとパスワード再確認フォームへの入力は必須。

だが、ログイン後のプロフィール編集等で、名前やメールアドレスの簡易な編集でいちいちパスワードを入力させるのはユーザーにとって手間。

新規登録のcreateアクションでのみパスワード再確認を実施し、プロフィール編集のeditアクションでは実施しない、ということを実現したい。

そのためのメモ。

user.rb
# パスワード再確認 onの後に指定したアクションでのみ動作するようになる
validates :password, confirmation: true, allow_nil: true, on: :create

validates :password
パスワード属性を検証する

confirmation: true
パスワード属性がtrue(一致しているか)であるかを確認する

on: :アクション名
このメソッドを実行するアクションを指定する

一致

指定した属性名と#{指定した属性名}_confirmationを比較します。
(この場合email属性)

model
validates :email, confirmation: true

上記のようにしたが、パスワードを変更したい場合にバリデーションがかからなかったので、最終的に以下のように修正しました。

パスワード入力用
# allow_nil: trueの場合、nilを認める
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

パスワード再確認用  
# confirmation: trueで、パスワードとパスワード再確認が一致するかを検証する。
パスワード入力用がnilの場合もあるため、こちらでもallow_nil: trueを追加し、nil同士の検証も出来るようにする。

validates :password, confirmation: true, allow_nil: true

参考
Railsバリデーションまとめ

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