rails-dev
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCommunity Ruby on Rails Development Best Practices
社区维护的Ruby on Rails开发最佳实践
Comprehensive performance and maintainability optimization guide for Ruby on Rails applications, maintained by Community. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
本指南是由社区维护的Ruby on Rails应用性能与可维护性优化综合指南,包含8个分类下的45条规则,按影响优先级排序,可指导自动化重构与代码生成。
When to Apply
适用场景
Reference these guidelines when:
- Writing new Rails controllers, models, or views
- Optimizing ActiveRecord queries and database access patterns
- Implementing caching strategies (fragment, Russian doll, low-level)
- Building or refactoring API endpoints
- Adding Turbo Frames and Streams for interactive UIs
- Reviewing code for N+1 queries and security vulnerabilities
- Designing background jobs with Sidekiq or Active Job
- Writing or reviewing database migrations
在以下场景中参考本指南:
- 编写新的Rails控制器、模型或视图
- 优化ActiveRecord查询与数据库访问模式
- 实现缓存策略(片段缓存、Russian doll缓存、底层缓存)
- 构建或重构API端点
- 为交互式UI添加Turbo Frames与Streams
- 评审代码以排查N+1查询与安全漏洞
- 使用Sidekiq或Active Job设计后台任务
- 编写或评审数据库迁移
Rule Categories by Priority
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Database & ActiveRecord | CRITICAL | |
| 2 | Controllers & Routing | CRITICAL | |
| 3 | Security | HIGH | |
| 4 | Models & Business Logic | HIGH | |
| 5 | Caching & Performance | HIGH | |
| 6 | Views & Frontend | MEDIUM-HIGH | |
| 7 | API Design | MEDIUM | |
| 8 | Background Jobs & Async | LOW-MEDIUM | |
| 优先级 | 分类 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 数据库与ActiveRecord | 关键 | |
| 2 | 控制器与路由 | 关键 | |
| 3 | 安全 | 高 | |
| 4 | 模型与业务逻辑 | 高 | |
| 5 | 缓存与性能 | 高 | |
| 6 | 视图与前端 | 中高 | |
| 7 | API设计 | 中 | |
| 8 | 后台任务与异步处理 | 中低 | |
Quick Reference
快速参考
1. Database & ActiveRecord (CRITICAL)
1. 数据库与ActiveRecord(关键)
- - Eager load associations to eliminate N+1 queries
db-eager-load-associations - - Add database indexes on queried columns
db-add-database-indexes - - Select only needed columns
db-select-specific-columns - - Use find_each for large dataset iteration
db-batch-processing - - Avoid database queries inside loops
db-avoid-queries-in-loops - - Define reusable query scopes on models
db-use-scopes - - Write reversible zero-downtime migrations
db-safe-migrations - - Use exists? instead of count for existence checks
db-exists-over-count
- - 预加载关联以消除N+1查询
db-eager-load-associations - - 为查询字段添加数据库索引
db-add-database-indexes - - 仅选择所需字段
db-select-specific-columns - - 使用find_each处理大型数据集迭代
db-batch-processing - - 避免在循环中执行数据库查询
db-avoid-queries-in-loops - - 在模型上定义可复用的查询作用域
db-use-scopes - - 编写可回滚的零停机数据库迁移
db-safe-migrations - - 检查存在性时使用exists?而非count
db-exists-over-count
2. Controllers & Routing (CRITICAL)
2. 控制器与路由(关键)
- - Keep controllers thin by delegating to models and services
ctrl-thin-controllers - - Always use strong parameters for mass assignment
ctrl-strong-params - - Follow RESTful routing conventions
ctrl-restful-routes - - Scope before_action callbacks with only/except
ctrl-before-action-scoping - - Use respond_to for multi-format responses
ctrl-respond-to-format - - Handle errors with rescue_from in controllers
ctrl-rescue-from
- - 保持控制器轻量化,将逻辑委托给模型与服务对象
ctrl-thin-controllers - - 始终使用强参数进行批量赋值
ctrl-strong-params - - 遵循RESTful路由规范
ctrl-restful-routes - - 使用only/except限制before_action回调的作用范围
ctrl-before-action-scoping - - 使用respond_to处理多格式响应
ctrl-respond-to-format - - 在控制器中使用rescue_from处理错误
ctrl-rescue-from
3. Security (HIGH)
3. 安全(高)
- - Never interpolate user input in SQL
sec-parameterized-queries - - Whitelist permitted params, never blacklist
sec-strong-params-whitelist - - Authenticate before authorize on every request
sec-authenticate-before-authorize - - Enable CSRF protection for all form submissions
sec-csrf-protection - - Scope queries to current user for authorization
sec-scope-queries-to-user
- - 切勿在SQL中直接插入用户输入
sec-parameterized-queries - - 对允许的参数使用白名单,而非黑名单
sec-strong-params-whitelist - - 每个请求都要先认证再授权
sec-authenticate-before-authorize - - 为所有表单提交启用CSRF保护
sec-csrf-protection - - 为查询添加当前用户的作用域以实现授权
sec-scope-queries-to-user
4. Models & Business Logic (HIGH)
4. 模型与业务逻辑(高)
- - Validate data at the model level
model-validate-at-model-level - - Avoid side effects in model callbacks
model-avoid-callback-side-effects - - Extract complex logic into service objects
model-use-service-objects - - Use scopes instead of class methods for query composition
model-scope-over-class-methods - - Use enums for finite state fields
model-use-enums - - Use concerns for shared model behavior
model-concerns-for-shared-behavior - - Extract complex queries into query objects
model-query-objects
- - 在模型层验证数据
model-validate-at-model-level - - 避免在模型回调中产生副作用
model-avoid-callback-side-effects - - 将复杂逻辑提取到服务对象中
model-use-service-objects - - 优先使用作用域而非类方法来组合查询
model-scope-over-class-methods - - 对有限状态字段使用枚举
model-use-enums - - 使用concerns实现模型的共享行为
model-concerns-for-shared-behavior - - 将复杂查询提取到查询对象中
model-query-objects
5. Caching & Performance (HIGH)
5. 缓存与性能(高)
- - Use fragment caching for expensive view partials
cache-fragment-caching - - Use Russian doll caching for nested collections
cache-russian-doll - - Use Rails.cache.fetch for computed data
cache-low-level - - Use counter caches for association counts
cache-counter-cache - - Use conditional GET with stale? for HTTP caching
cache-conditional-get
- - 对开销较大的视图部分使用片段缓存
cache-fragment-caching - - 对嵌套集合使用Russian doll缓存
cache-russian-doll - - 使用Rails.cache.fetch缓存计算数据
cache-low-level - - 对关联计数使用计数器缓存
cache-counter-cache - - 使用stale?实现HTTP条件GET缓存
cache-conditional-get
6. Views & Frontend (MEDIUM-HIGH)
6. 视图与前端(中高)
- - Use collection rendering instead of loop partials
view-collection-rendering - - Use Turbo Frames for partial page updates
view-turbo-frames - - Use Turbo Streams for real-time page mutations
view-turbo-streams - - Use form_with instead of form_tag or form_for
view-form-with - - Move display logic to helpers or presenters
view-avoid-logic-in-views
- - 使用集合渲染而非循环渲染局部视图
view-collection-rendering - - 使用Turbo Frames实现页面局部更新
view-turbo-frames - - 使用Turbo Streams实现实时页面变更
view-turbo-streams - - 使用form_with而非form_tag或form_for
view-form-with - - 将显示逻辑移至助手或展示器中
view-avoid-logic-in-views
7. API Design (MEDIUM)
7. API设计(中)
- - Use serializers for consistent JSON responses
api-serializers - - Always paginate collection endpoints
api-pagination - - Version APIs from day one
api-versioning - - Return structured error responses
api-error-responses - - Avoid Jbuilder on high-traffic endpoints
api-avoid-jbuilder-hot-paths
- - 使用序列化器生成一致的JSON响应
api-serializers - - 集合端点始终实现分页
api-pagination - - 从第一天开始为API添加版本控制
api-versioning - - 返回结构化的错误响应
api-error-responses - - 高流量端点避免使用Jbuilder
api-avoid-jbuilder-hot-paths
8. Background Jobs & Async (LOW-MEDIUM)
8. 后台任务与异步处理(中低)
- - Design jobs to be idempotent
job-idempotent-design - - Pass IDs to jobs, not serialized objects
job-small-payloads - - Configure retry and error handling for jobs
job-error-handling - - Prevent duplicate job enqueuing
job-unique-jobs
- - 设计幂等的后台任务
job-idempotent-design - - 向任务传递ID而非序列化对象
job-small-payloads - - 配置任务的重试与错误处理机制
job-error-handling - - 防止重复入队后台任务
job-unique-jobs
How to Use
使用方法
Read individual reference files for detailed explanations and code examples:
- Section definitions - Category structure and impact levels
- Rule template - Template for adding new rules
阅读单个参考文件获取详细说明与代码示例:
- 分类定义 - 分类结构与影响级别说明
- 规则模板 - 添加新规则的模板
Reference Files
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 分类定义与排序规则 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |