🐷

Railsチュートリアル「11.3.1 authenticated?メソッドの抽象化」の演習2が`false`になる時の対処

3 min read

事象

Railsチュートリアル「11.3.1 authenticated?メソッドの抽象化」の演習2のauthenticated?メソッドがtrueにならず、falseになる。

対処

db/seeds.rbを参考にuserオブジェクトを作成。

[2] pry(main)> user = User.new(name: 'kappy-',
[2] pry(main)*   email: 'kappy-@nikoniko.com',  
[2] pry(main)*   password: 'kappy-',  
[2] pry(main)*   password_confirmation: 'kappy-',  
[2] pry(main)*   activated: true,  
[2] pry(main)*   activated_at: Time.zone.now)
=> #<User:0x000055f08655eca0
 id: nil,
 name: "kappy-",
 email: "kappy-@nikoniko.com",
 created_at: nil,
 updated_at: nil,
 password_digest: "[FILTERED]",
 remember_digest: nil,
 admin: false,
 activation_digest: nil,
 activated: true,
 activated_at: Sun, 17 Jan 2021 00:51:53 UTC +00:00>

remember_tokenに新しいトークンを作成。

[3] pry(main)> user.remember_token = User.new_token
=> "5T5kP80PvNUcHKNKVwu4Fw"

remember_tokenを使ってremember_digestを設定。

[4] pry(main)> user.update_attribute(:remember_digest, User.digest(user.remember_token))
   (0.3ms)  BEGIN
  User Create (3.3ms)  INSERT INTO "users" ("name", "email", "created_at", "updated_at", "password_digest", "remember_digest", "activation_digest", "activated", "activated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id"  [["name", "kappy-"], ["email", "kappy-@nikoniko.com"], ["created_at", "2021-01-17 01:02:09.022858"], ["updated_at", "2021-01-17 01:02:09.022858"], ["password_digest", "$2a$12$U8dlalylRNa67F2w7gMyW.XHBvR1XEe1htUU/WXwq1kxs90yQT.mG"], ["remember_digest", "$2a$12$C7f0BKY6CXjZ/tkKKRLBienkHBP20L8X5ComTnW.3ibI2.PNwRJ/y"], ["activation_digest", "$2a$12$FIKkeRneEDG7uBISj6.ebOLnzLOeh7IzKhWks3URS9cJQzEYfTRNG"], ["activated", true], ["activated_at", "2021-01-17 00:51:53.410158"]]
   (1.3ms)  COMMIT
=> true

remember_digestが設定されていることを確認。

[5] pry(main)> user
=> #<User:0x000055f08655eca0
 id: 104,
 name: "kappy-",
 email: "kappy-@nikoniko.com",
 created_at: Sun, 17 Jan 2021 01:02:09 UTC +00:00,
 updated_at: Sun, 17 Jan 2021 01:02:09 UTC +00:00,
 password_digest: "[FILTERED]",
 remember_digest: "$2a$12$C7f0BKY6CXjZ/tkKKRLBienkHBP20L8X5ComTnW.3ibI2.PNwRJ/y",
 admin: false,
 activation_digest: "$2a$12$FIKkeRneEDG7uBISj6.ebOLnzLOeh7IzKhWks3URS9cJQzEYfTRNG",
 activated: true,
 activated_at: Sun, 17 Jan 2021 00:51:53 UTC +00:00>

remember_tokenの値を確認してから、
authenticated?メソッドを使い、トークン/ダイジェストの組み合わせで認証が成功することを確認。

[6] pry(main)> user.remember_token
=> "5T5kP80PvNUcHKNKVwu4Fw"
[7] pry(main)> user.authenticated?(:remember, "5T5kP80PvNUcHKNKVwu4Fw")
=> true

trueになりました。

参考

【11章】Ruby on Railsチュートリアル演習まとめ&解答例【11.3 アカウントを有効化する】

Discussion

ログインするとコメントできます