首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Rails 開發核心約定與常用命令速查:從項目創建到模型關聯的最佳實踐

     編輯:Java 相關知識

核心命令速查表

任務命令說明
創建新應用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:textModel+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交互式調試環境

Rails 約定大於配置:三大核心約定

1. 表名約定

  • 模型類名單數、駝峰(Sheep、User)。
  • 表名復數、小寫、下劃線(sheeps、users、line_items)。
  • 覆蓋:self.table_name = "custom_table_name"。

2. 主鍵約定

  • 默認主鍵列名 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"

3. 模型關聯約定

三種基本關係,四個聲明方法:

關係聲明外鍵位置核心規則
一對一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   # 測試配置

避坑指南:常見約定違背後果

  1. 表名不遵循復數:需處處指定 table_name,關聯 class_name、foreign_key 全手寫。
  2. 主鍵非 id 未覆蓋 primary_key:find、關聯查詢全報錯。
  3. 外鍵列名不符合 模型名_id:關聯必須加 foreign_key。
  4. 多對多用 HABTM 卻需存中間屬性:必須遷移至 has_many :through。
  5. 模型文件名與類名不匹配:user.rb 定義 class User,否則自動加載失敗。

總結

Rails 的生產力源於「約定大於配置」。內化三大核心約定(表名、主鍵、關聯),熟練掌握生成命令,就能在幾分鐘內搭建起具備完整 CRUD、測試、遷移的生產級骨架。記住:順應約定是捷徑,違背約定是債——除非有極強理由(如對接legacy庫),否則請擁抱約定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved