Debug and Rails environments
使用者的資訊頁面會是我們第一個在這個 APP 中真正的動態頁面。view 中的程式碼不會動態改變,但每個使用者的資訊頁面所顯示的內容都是從資料庫裡讀取。在增加動態頁面之前,最好做一些準備工作,我們要在 application.html.erb 中增加除錯訊息:
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
.
.
.
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
<%= render 'layouts/footer' %>
<%= debug(params) if Rails.env.development? %>
</div>
</body>
</html>
<%= debug(params) if Rails.env.development? %> 這行使用 Rails 內建的 debug 方法和 params 變數,可以在各個頁面顯示一些對開發有幫助的訊息。
if Rails.env.development? 這段則是設定除錯訊息只限在 development 環境中顯示,因為我們並不想讓使用者在 production 環境看到。而它只會在 development 環境中才會回傳 true。(也不會在 test 環境中看到)
為了讓除錯訊息看起來順眼一點,可以加一下樣式:
app/assets/stylesheets/custom.css.sass
@import "bootstrap-sprockets"
@import "bootstrap"
/* mixins, variables, etc. */
$gray-medium-light: #eaeaea
@mixin box_sizing
-moz-box-sizing: border-box
-webkit-box-sizing: border-box
box-sizing: border-box
.
.
.
/* miscellaneous */
.debug_dump
clear: both
float: left
width: 100%
margin-top: 45px
@include box_sizing
最後頁面看起來會像這樣:

頁面中的除錯訊息:
---
controller: static_pages
action: home
這是 params 變數用 YAML 格式呈現,本質上是一個 Hash,就這頁來說它顯示了 controller 和 action 的名稱。
Rails 的除錯訊息是用 YAML(YAML Ain't Markup Language 的簡稱,是個 recursive acronym),這個資料格式對於機器或是人類都可輕鬆閱讀。
Rails environments
Rails 定義三個環境:test、development、production。Rails console 預設的環境是 development:
$ rails console
Loading development environment
>> Rails.env
=> "development"
>> Rails.env.development?
=> true
>> Rails.env.test?
=> false
Rails 物件有一個 env 屬性,可以對 env 調用各個環境的 boolean,例如 Rails.env.test?,如果在 test 環境就回傳 true,反之回傳 false。
如果要在 console 使用不同的環境,只要把環境名稱傳給 console 即可:
$ rails console test
Loading test environment
>> Rails.env
=> "test"
>> Rails.env.test?
=> true
Rails server 和 console 一樣,預設環境都是 development,但也可以在其他環境執行:
$ rails server --environment production
如果要在 production 環境中執行,必須要有 production 環境的資料庫,所以要在 production 環境中執行 rake db:migrate:
$ bundle exec rake db:migrate RAILS_ENV=production
如果把 APP 部署到 Heroku 之後,可以使用 heroku run console 進入 console 查看使用的環境:
$ heroku run console
>> Rails.env
=> "production"
>> Rails.env.production?
=> true
不過 Heroku 是用來部署的網站平台,所以環境自然就是 production。