LoginSignup
11
7

More than 5 years have passed since last update.

Deviseのパスワードリセットのチェック項目を増やす

Posted at

deviseを使っていてパスワードリセットを行うとき、
登録したメールアドレスを入力します。
が、その時に入力する項目を増やす必要がありました。

このときどうしたら良いかわからなかったのでがんばって調べた。

結果だけ先に

deviseを使っているモデルに

user.rb
def self.reset_password_keys
  %i( email hoge fuga )
end

のようなクラスメソッドを追加し、

app/views/devise/passwords/new.html.erbに、
hoge fugaの入力フォームを追加すればできた。

詳しく

(詳しくは無いけど)
パスワードリセットはpasswords_controllercreateアクションなので、
そこを見る。
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/passwords_controller.rb#L12

passwords_controller.rb
  def create
    self.resource = resource_class.send_reset_password_instructions(resource_params)
    yield resource if block_given?

    if successfully_sent?(resource)
      respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name))
    else
      respond_with(resource)
    end
  end

resource_class.send_reset_password_instructionsのなかでモデルを探しているっぽいので中を見る。
と、
https://github.com/plataformatec/devise/blob/1a0192201b317d3f1bac88f5c5b4926d527b1b39/lib/devise/models/recoverable.rb#L126

recoverable.rb
def send_reset_password_instructions(attributes={})
  recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
  recoverable.send_reset_password_instructions if recoverable.persisted?
  recoverable
end

find_or_initialize_with_errorsが探してあるかないかエラー付きで返してくれるっぽい。

def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc:
  attributes = attributes.slice(*required_attributes).with_indifferent_access
  attributes.delete_if { |key, value| value.blank? }

  if attributes.size == required_attributes.size
    record = find_first_by_auth_conditions(attributes)
  end

  unless record
    record = new

    required_attributes.each do |key|
      value = attributes[key]
      record.send("#{key}=", value)
      record.errors.add(key, value.present? ? error : :blank)
    end
  end

  record
end

attributesからrequired_attributesに設定されたキーでDBから検索して、
その結果recordが無ければ、エラーを追加する。のようになっていました。

なのでrequired_attributesにチェックしたい項目を追加していけば良いので、
つまりreset_password_keysにチェックしたい項目を追加していけば良い。となりました。

まとめ

最初に書いた通り、reset_password_keysにシンボル追加するだけでいい感じになりました。

感想

なんかこんな書き方しなくてもいいんじゃないかな。とか結構思いますが、僕のググり力の低さと英語読みたく無い力が相俟って、こんな風になってしまいました。

もしここまで読んでくださった方で、「こうすればすぐできるのに」とか「バッカジャネーノ!」という方がいらっしゃったら教えていただけたら幸いです。。。

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