長期深耕 Java EE:Struts → Spring → Hibernate → EJB3 → JPA → 各種 XML、Annotation、DAO、Service、DTO、VO… 層層包裝、樣板碼堆疊、**「為了寫一個 CRUD 要建十個檔案」**成為常態。聽說 Ruby on Rails (RoR)「幾行代碼搞定部落格」,抱著懷疑態度按 Rails 4 Days 教程實操,三天後世界觀重塑。
# 安裝 Ruby + Rails (Windows 安裝包一鍵搞定)
gem install rails
# 生成完整 Web 應用骨架
rails new myblog
cd myblog
# 配置資料庫 (config/database.yml) - YAML 而非 XML
# 建立資料表
rails db:migrate
**無容器配置、無 JNDI、無 web.xml、無 persistence.xml、無 Spring context**。
# 一行指令生成 Model + Migration + Controller + Views + Routes + Tests
rails generate scaffold Post title:string body:text published:boolean
# 遷移資料庫
rails db:migrate
# 啟動開發伺服器
rails server
瀏覽 https://localhost:3000/posts —— **完整的列表/新增/編輯/刪除/驗證/分頁/JSON API 全部就緒**。
# Controller
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: '文章已建立'
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :body, :published) # 強參數防禦
end
# Model (ActiveRecord)
class Post < ApplicationRecord
validates :title, presence: true, length: { minimum: 5 }
scope :published, -> { where(published: true) }
end
# View (ERB - 類 JSP 但更精簡)
<%= form_with model: @post do |f| %>
<%= f.label :title %><%= f.text_field :title %>
<%= f.submit %>
<% end %>
rails console 進入 IRB,直接操作 ActiveRecord 物件驗證邏輯常見質疑:「動態語言慢、不適合大型系統」。實測數據 (社區基準測試):**RoR 吞吐量超越 Spring+Hibernate+Struts 15-20%**,開發速度 **>10x**。原因:
**關鍵認知**:Web 應用瓶頸 90% 在 **資料庫/網絡/鎖爭用**,語言執行速度很少是主因。RoR 用「開發效率換取硬體成本」在多數商業場景極具性價比。
| 擔憂 | 現狀回應 |
|---|---|
| 大型應用支撐? | GitHub, Shopify, Airbnb, Basecamp, Coinbase 皆為 Rails 核心架構,支撐百萬級日活 |
| 長期維護? | Rails 7.1 (2023) 持續釋出,核心團隊穩定,LTS 政策明確 |
| 人才招募? | Ruby 社區雖小但高質量,薪資具競爭力,轉型成本低 |
| 前後端分離? | Rails 7+ 原生支援 Hotwire (Turbo + Stimulus) 實現 SPA 體驗無需重前端框架 |
| 微服務? | 可作為 API Only 模式 (rails new --api) 或模塊化單體 |