Logging in
登入表單已經可以處理無效資料的提交,接著要正確處理有效的提交,讓使用者登入。我們要讓使用者透過短暫 session 的 cookie 登入,直到關閉瀏覽器就自動失效。之後會實作就算關閉瀏覽器,依然處於登入狀態。
實作 sessions 會定義很多相關的函式,而且要跨多個 controllers 和 views 使用。我們可以使用 Ruby 提供的 module ,把函示集中在裡面。在建立 Sessions controller 的時候,其實 Rails 就自動幫你產生 Sessions helper module。其中的 helpers 也會自動被引入 Rails views。如果在 controllers 的 Basic Class(Application controller)引入 helper module,還可以在 controllers 中使用:
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end