rails-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Community 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

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Database & ActiveRecordCRITICAL
db-
2Controllers & RoutingCRITICAL
ctrl-
3SecurityHIGH
sec-
4Models & Business LogicHIGH
model-
5Caching & PerformanceHIGH
cache-
6Views & FrontendMEDIUM-HIGH
view-
7API DesignMEDIUM
api-
8Background Jobs & AsyncLOW-MEDIUM
job-
优先级分类影响程度前缀
1数据库与ActiveRecord关键
db-
2控制器与路由关键
ctrl-
3安全
sec-
4模型与业务逻辑
model-
5缓存与性能
cache-
6视图与前端中高
view-
7API设计
api-
8后台任务与异步处理中低
job-

Quick Reference

快速参考

1. Database & ActiveRecord (CRITICAL)

1. 数据库与ActiveRecord(关键)

  • db-eager-load-associations
    - Eager load associations to eliminate N+1 queries
  • db-add-database-indexes
    - Add database indexes on queried columns
  • db-select-specific-columns
    - Select only needed columns
  • db-batch-processing
    - Use find_each for large dataset iteration
  • db-avoid-queries-in-loops
    - Avoid database queries inside loops
  • db-use-scopes
    - Define reusable query scopes on models
  • db-safe-migrations
    - Write reversible zero-downtime migrations
  • db-exists-over-count
    - Use exists? instead of count for existence checks
  • db-eager-load-associations
    - 预加载关联以消除N+1查询
  • db-add-database-indexes
    - 为查询字段添加数据库索引
  • db-select-specific-columns
    - 仅选择所需字段
  • db-batch-processing
    - 使用find_each处理大型数据集迭代
  • db-avoid-queries-in-loops
    - 避免在循环中执行数据库查询
  • db-use-scopes
    - 在模型上定义可复用的查询作用域
  • db-safe-migrations
    - 编写可回滚的零停机数据库迁移
  • db-exists-over-count
    - 检查存在性时使用exists?而非count

2. Controllers & Routing (CRITICAL)

2. 控制器与路由(关键)

  • ctrl-thin-controllers
    - Keep controllers thin by delegating to models and services
  • ctrl-strong-params
    - Always use strong parameters for mass assignment
  • ctrl-restful-routes
    - Follow RESTful routing conventions
  • ctrl-before-action-scoping
    - Scope before_action callbacks with only/except
  • ctrl-respond-to-format
    - Use respond_to for multi-format responses
  • ctrl-rescue-from
    - Handle errors with rescue_from in controllers
  • ctrl-thin-controllers
    - 保持控制器轻量化,将逻辑委托给模型与服务对象
  • ctrl-strong-params
    - 始终使用强参数进行批量赋值
  • ctrl-restful-routes
    - 遵循RESTful路由规范
  • ctrl-before-action-scoping
    - 使用only/except限制before_action回调的作用范围
  • ctrl-respond-to-format
    - 使用respond_to处理多格式响应
  • ctrl-rescue-from
    - 在控制器中使用rescue_from处理错误

3. Security (HIGH)

3. 安全(高)

  • sec-parameterized-queries
    - Never interpolate user input in SQL
  • sec-strong-params-whitelist
    - Whitelist permitted params, never blacklist
  • sec-authenticate-before-authorize
    - Authenticate before authorize on every request
  • sec-csrf-protection
    - Enable CSRF protection for all form submissions
  • sec-scope-queries-to-user
    - Scope queries to current user for authorization
  • sec-parameterized-queries
    - 切勿在SQL中直接插入用户输入
  • sec-strong-params-whitelist
    - 对允许的参数使用白名单,而非黑名单
  • sec-authenticate-before-authorize
    - 每个请求都要先认证再授权
  • sec-csrf-protection
    - 为所有表单提交启用CSRF保护
  • sec-scope-queries-to-user
    - 为查询添加当前用户的作用域以实现授权

4. Models & Business Logic (HIGH)

4. 模型与业务逻辑(高)

  • model-validate-at-model-level
    - Validate data at the model level
  • model-avoid-callback-side-effects
    - Avoid side effects in model callbacks
  • model-use-service-objects
    - Extract complex logic into service objects
  • model-scope-over-class-methods
    - Use scopes instead of class methods for query composition
  • model-use-enums
    - Use enums for finite state fields
  • model-concerns-for-shared-behavior
    - Use concerns for shared model behavior
  • model-query-objects
    - Extract complex queries into query objects
  • model-validate-at-model-level
    - 在模型层验证数据
  • model-avoid-callback-side-effects
    - 避免在模型回调中产生副作用
  • model-use-service-objects
    - 将复杂逻辑提取到服务对象中
  • model-scope-over-class-methods
    - 优先使用作用域而非类方法来组合查询
  • model-use-enums
    - 对有限状态字段使用枚举
  • model-concerns-for-shared-behavior
    - 使用concerns实现模型的共享行为
  • model-query-objects
    - 将复杂查询提取到查询对象中

5. Caching & Performance (HIGH)

5. 缓存与性能(高)

  • cache-fragment-caching
    - Use fragment caching for expensive view partials
  • cache-russian-doll
    - Use Russian doll caching for nested collections
  • cache-low-level
    - Use Rails.cache.fetch for computed data
  • cache-counter-cache
    - Use counter caches for association counts
  • cache-conditional-get
    - Use conditional GET with stale? for HTTP caching
  • cache-fragment-caching
    - 对开销较大的视图部分使用片段缓存
  • cache-russian-doll
    - 对嵌套集合使用Russian doll缓存
  • cache-low-level
    - 使用Rails.cache.fetch缓存计算数据
  • cache-counter-cache
    - 对关联计数使用计数器缓存
  • cache-conditional-get
    - 使用stale?实现HTTP条件GET缓存

6. Views & Frontend (MEDIUM-HIGH)

6. 视图与前端(中高)

  • view-collection-rendering
    - Use collection rendering instead of loop partials
  • view-turbo-frames
    - Use Turbo Frames for partial page updates
  • view-turbo-streams
    - Use Turbo Streams for real-time page mutations
  • view-form-with
    - Use form_with instead of form_tag or form_for
  • view-avoid-logic-in-views
    - Move display logic to helpers or presenters
  • view-collection-rendering
    - 使用集合渲染而非循环渲染局部视图
  • view-turbo-frames
    - 使用Turbo Frames实现页面局部更新
  • view-turbo-streams
    - 使用Turbo Streams实现实时页面变更
  • view-form-with
    - 使用form_with而非form_tag或form_for
  • view-avoid-logic-in-views
    - 将显示逻辑移至助手或展示器中

7. API Design (MEDIUM)

7. API设计(中)

  • api-serializers
    - Use serializers for consistent JSON responses
  • api-pagination
    - Always paginate collection endpoints
  • api-versioning
    - Version APIs from day one
  • api-error-responses
    - Return structured error responses
  • api-avoid-jbuilder-hot-paths
    - Avoid Jbuilder on high-traffic endpoints
  • api-serializers
    - 使用序列化器生成一致的JSON响应
  • api-pagination
    - 集合端点始终实现分页
  • api-versioning
    - 从第一天开始为API添加版本控制
  • api-error-responses
    - 返回结构化的错误响应
  • api-avoid-jbuilder-hot-paths
    - 高流量端点避免使用Jbuilder

8. Background Jobs & Async (LOW-MEDIUM)

8. 后台任务与异步处理(中低)

  • job-idempotent-design
    - Design jobs to be idempotent
  • job-small-payloads
    - Pass IDs to jobs, not serialized objects
  • job-error-handling
    - Configure retry and error handling for jobs
  • job-unique-jobs
    - Prevent duplicate job enqueuing
  • job-idempotent-design
    - 设计幂等的后台任务
  • job-small-payloads
    - 向任务传递ID而非序列化对象
  • 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

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md分类定义与排序规则
assets/templates/_template.md新规则模板
metadata.json版本与参考信息