ユーザーの検索と認証
Sessionsコントローラのcreateアクション
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
# 新規ユーザー作成
render 'new'
# newアクションのビューを表示させる
end
def destroy
# ユーザー削除
end
end
デバッグ情報
paramsハッシュでは、次のようにsessionキーの下にメールアドレスとパスワード
--- !ruby/object:ActionController::Parameters
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
authenticity_token: s9oeKxILHYOKGNouY+o5HHYogso0J+Rba3NussPUvpHgdD3Q3SaRrwdoDXu2XRt/c+ykDJX9uFM+UMMlBGjh0g==
session: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
email: ''
password: ''
commit: Log in
controller: sessions
action: create
permitted: false
ハッシュのハッシュ
{ session: { password: "foobar", email: "user@example.com" } }
上を略すことができる
params[:session]
ハッシュのハッシュ
{ password: "foobar", email: "user@example.com" }
細かくハッシュの検索
params[:session][:email]
params[:session][:password]
ユーザーをデータベースから見つけて検証する
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
# 送信されたメアドを使ってデータベースから取り出す。
#emailを小文字にする
if user && user.authenticate(params[:session][:password])
# user 取得したユーザーが有効かどうか?
# その後にデータベース上にパスワードがあるか?
# ユーザーログイン後にユーザー情報のページにリダイレクトする
else
# エラーメッセージを作成する
render 'new'
# newアクションのビューを表示
end
end
def destroy
# ユーザー削除
end
end
演習
1.Railsコンソールを使って、表 8.2のそれぞれの式が合っているか確かめてみましょう. まずはuser = nilの場合を、次にuser = User.firstとした場合を確かめてみてください。ヒント: 必ず論理値オブジェクトとなるように、4.2.2で紹介した!!のテクニックを使ってみましょう。例: !!(user && user.authenticate('foobar'))
>> user = nil
=> nil
>> user.class
=> NilClass
>> user = User.first
(1.8ms) SELECT sqlite_version(*)
User Load (0.7ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<User id: 1, name: "a", email: "abc@def.com", created_at: "2021-10-0
>> !!(user && user.authenticate('foobar'))
=> false
作ったuserとデータベース上にあるuserを比べているらしい。