ActiveRecord 物件的屬性對應資料表欄位,提供多種存取方式,理解其差異有助於撰寫更符合慣例的程式碼。
account[:balance] # 讀取
account[:balance] = 0.0 # 寫入
雖然可行,但非 Ruby 慣用寫法,降低可讀性。
account.balance # 讀取
account.balance = 0.0 # 寫入
符合 Ruby 物件導向風格,程式碼清晰自然,是慣用做法。
ActiveRecord 會自動將資料庫型別轉換為 Ruby 物件(如 timestamp → Time)。若需取得資料庫原始字串值,在存取器後加 _before_type_cast:
account.balance_before_type_cast # => "123.4" (String)
account.release_date_before_type_cast # => "20050301" (String)
常用於表單顯示使用者原始輸入或匯出原始資料。
account.read_attribute(:balance) # 等同 account[:balance]
account.write_attribute(:balance, 0.0) # 等同 account[:balance] = 0.0
內部實作使用,極少在應用層直接呼叫。
| SQL 型別 | Ruby 類別 |
|---|---|
| int, integer | Fixnum |
| float, double | Float |
| decimal, numeric | Float (注意精度問題) |
| char, varchar, string | String |
| clob, blob, text | String |
| datetime, time | Time |
| date | Date |
| boolean | TrueClass/FalseClass |
資料庫 decimal 對應 Ruby Float,浮點數運算存在捨入誤差。貨幣計算建議:
composed_of 聚合多個欄位構建 Money 物件。