2005 年,Java 陣營擁有數百個 ORM (Hibernate, iBATIS, JDO...) 與 MVC (Struts, WebWork, Spring MVC, Tapestry...) 框架,卻陷入配置地獄、樣板代碼爆炸、開發效率低的泥沼。Rails 以約定優於配置、DRY (Don't Repeat Yourself)、Active Record、Action Pack 重新定義了生產力標準。
| 維度 | 傳統 Java 堆疊 | Rails |
|---|---|---|
| 代碼量 | Struts + Spring + Hibernate = 基準 | 1/N (CRUD 僅需 1 行 scaffold) |
| 效能 | 基準 | 快 15-30% (早期基準測試) |
| 語義表達 | 通用抽象語言 (Java/C#) | 領域特定語言 (DSL),代碼如自然語言 |
┌─────────────────────────────────────┐
│ Apache / Nginx │ ← 靜態資源、SSL 終結、反向代理
├─────────────────────────────────────┤
│ Rails App │
│ ┌─────────────┐ ┌───────────────┐ │
│ │ Action Pack │ │ Active Record │ │ ← 核心兩大支柱
│ │ (MVC) │ │ (ORM) │ │
│ └─────────────┘ └───────────────┘ │
│ ┌─────────────┐ ┌───────────────┐ │
│ │ View Template│ │ Generators │ │ ← ERB/HAML/Slim + 代碼生成
│ │ (ERB等) │ │ (scaffold等) │ │
│ └─────────────┘ └───────────────┘ │
└─────────────────────────────────────┘
# 模型定義 (app/models/user.rb)
class User < ApplicationRecord
has_many :posts
validates :email, presence: true, uniqueness: true
end
# 控制器自動獲得 CRUD (app/controllers/users_controller.rb)
class UsersController < ApplicationController
# scaffold 已生成 index, show, new, create, edit, update, destroy
end
# 路由一行搞定 (config/routes.rb)
resources :users
# 資料庫遷移 (db/migrate/xxx_create_users.rb)
class CreateUsers < ActiveRecord::Migration[7.0]
def change
create_table :users do |t|
t.string :email, null: false
t.string :name
t.timestamps
end
add_index :users, :email, unique: true
end
end
params[:user])、回應渲染 (render json: @user)$ rails new blog -d postgresql
$ cd blog
$ rails generate scaffold Post title:string body:text
$ rails db:create db:migrate
$ rails server
# 瀏覽器開啟 https://localhost:3000/posts
# 即擁有完整增刪改查、分頁、驗證、JSON API
| 類別 | 資源 |
|---|---|
| 官方指南 | Rails Guides (最佳入門) |
| 經典書籍 | Agile Web Development with Rails (Pragmatic Programmers) |
| Ruby 語言 | Ruby Doc / Learn to Program |
| 進階 | Rails Tutorial (Michael Hartl) / 社群 |
Rails 證明了「框架應服務於領域,而非領域服務於框架」。其極簡哲學——約定優於配置、DSL 表達領域、生成器消除樣板——深刻影響了後續所有現代框架 (Laravel, Django, Phoenix, Spring Boot, NestJS, Next.js...)。Java 開發者研讀 Rails,不為棄 Java 從 Ruby,而是為吸收其設計智慧,反哺自身技術棧:豐富領域模型、簡化配置、擁抱生成器、重視開發體驗。