| 任務 | 命令 | 說明 |
|---|---|---|
| 創建新應用 | rails new new_app | 生成標準目錄結構 |
| 創建數據庫 | rake db:create | 讀取 database.yml 配置 |
| 啟動開發服務器 | rails server | 默認 3000 端口 |
| 生成控制器 | rails g controller Blog action1 action2 | 含視圖、路由、測試、Helper、資源 |
| 生成 Scaffold(全棧) | rails g scaffold Product title:string description:text | Model+Migration+Controller+Views+Routes+Tests |
| 生成模型 | rails g model Comment commenter:string body:text post:references | 含外鍵、索引、關聯聲明 |
| 運行遷移 | rake db:migrate | 執行所有未跑遷移 |
| 回滾遷移 | rake db:rollback | 撤銷最後一個遷移 |
| 運行單元測試 | rake test:units | 或 rails test:units |
| 進入控制台 | rails console | 交互式調試環境 |
Sheep、User)。sheeps、users、line_items)。self.table_name = "custom_table_name"。id,類型 bigint,自增。@user.id 訪問。self.primary_key = "isbn"(模型屬性變為 isbn,但創建時仍用 id= 賦值)。class LegacyBook < ActiveRecord::Base self.primary_key = "isbn" end book = LegacyBook.new book.id = "1-214-985" # 必須用 id= 賦值 book.title = "Programming Ruby"
三種基本關係,四個聲明方法:
| 關係 | 聲明 | 外鍵位置 | 核心規則 |
|---|---|---|---|
| 一對一 | has_one / belongs_to | 從屬方表 | 包含外鍵的表必須聲明 belongs_to |
| 一對多 | has_many / belongs_to | 多方表 | 同上 |
| 多對多 | has_and_belongs_to_many (雙向) | 中間表 | 中間表名:兩表名字母序組合(categories_products),無 ID |
# 一對一:訂單 - 發票 class Order < ActiveRecord::Base has_one :invoice end class Invoice < ActiveRecord::Base belongs_to :order # invoices 表有 order_id end # 一對多:訂單 - 明細行 class Order < ActiveRecord::Base has_many :line_items end class LineItem < ActiveRecord::Base belongs_to :order # line_items 表有 order_id end # 多對多:產品 - 分類 class Product < ActiveRecord::Base has_and_belongs_to_many :categories end class Category < ActiveRecord::Base has_and_belongs_to_many :products end # 遷移:create_table :categories_products, id: false do |t| # t.integer :category_id; t.integer :product_id; end # 多對多進階:自定義中間模型(可存業務屬性) class Product < ActiveRecord::Base has_many :categorizations has_many :categories, through: :categorizations end class Categorization < ActiveRecord::Base belongs_to :product belongs_to :category # 可加屬性:added_at, added_by end class Category < ActiveRecord::Base has_many :categorizations has_many :products, through: :categorizations end
app/ ├── models/ # 業務模型、驗證、回調、關聯 ├── controllers/ # 請求處理、協調模型與視圖 ├── views/ # 模板(ERB/Haml/Slim) ├── helpers/ # 視圖輔助方法 ├── assets/ # JS/CSS/圖片 ├── mailers/ # 郵件模板 ├── jobs/ # 異步任務 ├── channels/ # ActionCable 實時通信 └── javascript/ # Webpacker/Importmaps 入口 config/ ├── routes.rb # 路由配置 ├── database.yml # 數據庫連接 ├── application.rb # 應用級配置 ├── environments/ # 三環境差異配置 └── initializers/ # 初始化腳本 db/ ├── migrate/ # 遷移文件 ├── schema.rb # 當前結構快照 └── seeds.rb # 初始數據 test/ ├── fixtures/ # 測試數據 ├── models/ # 單元測試 ├── controllers/ # 功能測試 ├── integration/ # 集成測試 └── test_helper.rb # 測試配置
table_name,關聯 class_name、foreign_key 全手寫。id 未覆蓋 primary_key:find、關聯查詢全報錯。模型名_id:關聯必須加 foreign_key。has_many :through。user.rb 定義 class User,否則自動加載失敗。Rails 的生產力源於「約定大於配置」。內化三大核心約定(表名、主鍵、關聯),熟練掌握生成命令,就能在幾分鐘內搭建起具備完整 CRUD、測試、遷移的生產級骨架。記住:順應約定是捷徑,違背約定是債——除非有極強理由(如對接legacy庫),否則請擁抱約定。