Conclusion

本章我們建立了有效的 User model,包含了 nameemailpassword 屬性,還有在這些屬性的值上面做了一些強制性的驗證功能。此外,也可以使用密碼對使用者進行驗證。只用了 12 行程式碼。

在下一章,會實作註冊表單、建立使用者帳戶,然後每個使用者都會有自己的個人帳戶頁面。接著後面也會使用 Adding a secure password 這個章節實作認證機制,讓使用者登入網站。

最後來提交一下:

$ bundle exec rake test
$ git add -A
$ git commit -m "Make a basic User model (including secure passwords)"

然後合併、push:

$ git checkout master
$ git merge modeling-users
$ git push

然後 deploy,為了能讓 User model 在 production 環境中使用,必須在 Heroku 上執行遷移:

$ bundle exec rake test
$ git push heroku
$ heroku run rake db:migrate

可以透過在 production 環境進入 console ,來確認遷移有沒有執行成功:

$ heroku run console --sandbox
> User.create(name: "Luffy Wang", email: "[email protected]", password: "foobar", password_confirmation: "foobar")
=> #<User id: 1, name: "Luffy Wang", email: "[email protected]", created_at: "2016-03-08 07:47:58", updated_at: "2016-03-08 07:47:58", password_digest: "$2a$10$4xPSoQdcg7p/zRiTu3PtPOEdoXaH6xTrnvj1ROKxo50...">

學到什麼?

  • 遷移檔案(Migrations)可以讓我們修改資料模型(data model)
  • Active Record 提供很多方法讓我們可以建立和操縱資料模型
  • Active Record 的驗證功能可以讓我們對 model 的資料設定限制條件
  • 一般驗證包括存在性驗證(presence)、長度驗證(length)和格式驗證(format)
  • 正規表示式很難懂,但很強大
  • 定義資料庫索引(database index)可以增進查詢效率,同時可以在資料庫裡實現唯一性的限制
  • 可以使用 Rails 內建的 has_secure_password 方法,在 model 增加安全密碼的設定