deviseを使っていてパスワードリセットを行うとき、
登録したメールアドレスを入力します。
が、その時に入力する項目を増やす必要がありました。
このときどうしたら良いかわからなかったのでがんばって調べた。
結果だけ先に
deviseを使っているモデルに
def self.reset_password_keys
%i( email hoge fuga )
end
のようなクラスメソッドを追加し、
app/views/devise/passwords/new.html.erb
に、
hoge
fuga
の入力フォームを追加すればできた。
詳しく
(詳しくは無いけど)
パスワードリセットはpasswords_controller
のcreate
アクションなので、
そこを見る。
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/passwords_controller.rb#L12
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
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
にシンボル追加するだけでいい感じになりました。
感想
なんかこんな書き方しなくてもいいんじゃないかな。とか結構思いますが、僕のググり力の低さと英語読みたく無い力が相俟って、こんな風になってしまいました。
もしここまで読んでくださった方で、「こうすればすぐできるのに」とか「バッカジャネーノ!」という方がいらっしゃったら教えていただけたら幸いです。。。