ActiveRecord 是 Rails 內建的物件關聯映射(ORM)層,遵循 Martin Fowler 的 Active Record 模式:
與傳統 ORM 大量依賴 XML 配置不同,ActiveRecord 採用「慣例優於配置」,極大減少樣板程式碼。
require "rubygems"
require_gem "activerecord"
# 建立資料庫連線
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "railsdb"
)
# 定義模型(零配置)
class Order < ActiveRecord::Base
end
# 使用模型
order = Order.find(123)
order.name = "Dave Thomas"
order.save
無任何映射配置檔,ActiveRecord 自動推斷表名、欄位、主鍵等。
| 類別名 | 推斷表名 |
|---|---|
| Order | orders |
| LineItem | line_items |
| TaxAgency | tax_agencies |
| Person | people |
| Diagnosis | diagnoses |
| Quantity | quantities |
| Batch | batches |
| Datum | data |
規則:類別單數、表名複數;多字類別以底線分隔(蛇形命名)後複數化。不規則複數(如 Person→people)內建支援。
# config/environment.rb
ActiveRecord::Base.pluralize_table_names = false
class Sheep < ActiveRecord::Base
set_table_name "sheep" # 避免變成 sheeps
end
class Order < ActiveRecord::Base
set_table_name "ord_rev99_x" # 對接舊有資料表
end
class Order < ActiveRecord::Base 觸發元程式設計機制。information_schema 取得欄位、型別、主鍵等中繼資料。attr_accessor 風格的讀寫方法。find, save, destroy 等。has_many, belongs_to 等)validates_presence_of 等)before_save, after_create 等)