rails
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<objective>
Provide comprehensive guidance for Ruby on Rails development based on the official Rails Guides v8.1.1. Use this skill for all Rails-related development tasks, from basic CRUD operations to advanced features like Action Cable, Active Job, and performance tuning.
</objective>
<context>
Rails follows the "Convention over Configuration" principle. When building Rails applications:
- Follow Rails naming conventions for models, controllers, and routes
- Use Rails generators for consistency
- Leverage Rails magic (associations, validations, callbacks) rather than reinventing
- Write tests using Rails testing conventions
- Use Rails helpers and built-in functionality before custom code </context>
<quick_start>
<common_commands>
bash
undefined<objective>
基于官方Rails Guides v8.1.1,提供全面的Ruby on Rails开发指导。所有与Rails相关的开发任务,从基础CRUD操作到Action Cable、Active Job和性能调优等高级功能,都可使用本技能。
</objective>
<context>
Rails遵循“约定优于配置”原则。在构建Rails应用时:
- 遵循Rails的模型、控制器和路由命名约定
- 使用Rails生成器以保持一致性
- 利用Rails的“魔法特性”(关联、验证、回调),而非重复造轮子
- 按照Rails测试约定编写测试
- 优先使用Rails助手方法和内置功能,再考虑自定义代码 </context>
<quick_start>
<common_commands>
bash
undefinedDatabase
Database
rails db:create # Create database
rails db:migrate # Run pending migrations
rails db:rollback # Rollback last migration
rails db:create # Create database
rails db:migrate # Run pending migrations
rails db:rollback # Rollback last migration
Console and server
Console and server
rails console # Start Rails console
rails server # Start development server
rails test # Run all tests
rails console # Start Rails console
rails server # Start development server
rails test # Run all tests
Generators
Generators
rails generate model NAME # Generate model
rails generate controller NAME # Generate controller
rails generate scaffold NAME # Generate full CRUD
</common_commands>
<typical_workflow>
1. Generate model: `rails generate model Article title:string body:text`
2. Run migration: `rails db:migrate`
3. Add associations and validations to model
4. Generate controller: `rails generate controller Articles`
5. Define routes in `config/routes.rb`
6. Build views with ERB templates
7. Write tests and iterate
</typical_workflow>
</quick_start>
<reference_guides>
This skill includes detailed reference documentation organized by topic. **Always consult the relevant reference file** when working on specific Rails components:
**Active Record** ([references/active_record.md](references/active_record.md))
Read this when working with:
- Models and database operations (CRUD, queries, scopes)
- Database migrations and schema changes
- Model associations (has_many, belongs_to, has_one, has_and_belongs_to_many)
- Validations and custom validators
- Callbacks and lifecycle hooks
- PostgreSQL-specific features
- Multiple database configurations
- Composite primary keys
- Encryption
Common patterns:
- Defining associations: Always specify inverse_of for better performance
- Writing migrations: Use reversible changes when possible
- Query optimization: Use includes/joins to avoid N+1 queries
- Validations: Validate at the model level, not just in controllers
**Controllers & Views** ([references/controllers_views.md](references/controllers_views.md))
Read this when working with:
- Action Controller basics and advanced topics
- Rendering views, partials, and layouts
- Strong parameters and params handling
- Action View helpers and form builders
- Request/response cycle
- Filters (before_action, after_action, around_action)
- Streaming and file downloads
Common patterns:
- Use strong parameters to whitelist permitted attributes
- Keep controllers thin - business logic belongs in models
- Use partials for reusable view components
- Leverage view helpers for common formatting tasks
**Routing** ([references/routing.md](references/routing.md))
Read this when working with:
- Defining routes (resources, match, get, post, etc.)
- RESTful routing conventions
- Nested routes and namespaces
- Route constraints and custom matchers
- Route helpers and URL generation
- Routing concerns for DRY routes
Common patterns:
- Use `resources` for RESTful routes
- Nest routes only when truly hierarchical (limit to 1 level deep)
- Use shallow nesting for cleaner URLs
- Utilize route concerns for shared routing patterns
**Testing & Debugging** ([references/testing_debugging.md](references/testing_debugging.md))
Read this when working with:
- Writing unit tests (models, helpers)
- Controller tests and integration tests
- System tests with browser automation
- Fixtures, factories, and test data
- Testing mailers, jobs, and cables
- Debugging techniques (byebug, rails console)
- Rails logger and debugging helpers
Common patterns:
- Write tests first (TDD) or immediately after (test-driven design)
- Use fixtures for simple cases, factories for complex scenarios
- Test edge cases and error conditions
- Use system tests for critical user flows
**Jobs, Mailers & Cable** ([references/jobs_mailers_cable.md](references/jobs_mailers_cable.md))
Read this when working with:
- Active Job for background processing
- Action Mailer for email sending
- Action Mailbox for receiving emails
- Action Cable for WebSocket connections
- Queue adapters (Sidekiq, Resque, etc.)
- Email delivery and testing
Common patterns:
- Always use Active Job for async work (don't block requests)
- Test mailers with ActionMailer::TestCase
- Use Action Cable for real-time features (chat, notifications)
- Configure proper queue backends for production
**Assets & Frontend** ([references/assets_frontend.md](references/assets_frontend.md))
Read this when working with:
- Asset pipeline and Sprockets
- JavaScript bundling (import maps, esbuild, webpack)
- CSS and preprocessors (Sass, Tailwind)
- Action Text for rich text editing
- Frontend frameworks integration
Common patterns:
- Use asset helpers (image_tag, javascript_include_tag, etc.)
- Configure proper asset compilation for production
- Leverage Rails UJS/Turbo for dynamic interactions
- Use Action Text for WYSIWYG content
**Storage & Caching** ([references/storage_caching.md](references/storage_caching.md))
Read this when working with:
- Active Storage for file uploads
- Attaching files to models
- Image variants and transformations
- Caching strategies (page, action, fragment, low-level)
- Cache stores (Redis, Memcached)
- Russian Doll caching patterns
Common patterns:
- Use Active Storage for all file uploads
- Generate image variants on-demand
- Cache expensive computations and queries
- Use fragment caching for dynamic pages
**Configuration & Internals** ([references/configuration_internals.md](references/configuration_internals.md))
Read this when working with:
- Rails configuration options
- Environment-specific settings
- Initialization process
- Autoloading and eager loading
- Threading and concurrency
- Rack integration
- Rails engines
- Command-line tools and generators
- Custom generators
Common patterns:
- Keep environment configs DRY using shared settings
- Use Rails.application.config for app-wide settings
- Understand autoloading in development vs eager loading in production
- Create custom generators for repeated patterns
**Security & Performance** ([references/security_performance.md](references/security_performance.md))
Read this when working with:
- Security best practices
- XSS, CSRF, SQL injection prevention
- Authentication and authorization patterns
- Performance tuning and optimization
- Database query optimization
- Asset optimization
- Error reporting and monitoring
Common patterns:
- Always use strong parameters (never trust user input)
- Enable CSRF protection (on by default)
- Use prepared statements to prevent SQL injection
- Add database indexes for frequently queried columns
- Profile before optimizing (use tools like rack-mini-profiler)
**I18n & Support** ([references/i18n_support.md](references/i18n_support.md))
Read this when working with:
- Internationalization (I18n) setup
- Locale files and translations
- Active Support core extensions
- Time zones and date formatting
- Active Support instrumentation
- Custom extensions and monkey patches
Common patterns:
- Use I18n.t for all user-facing strings
- Organize translations by controller/view hierarchy
- Leverage Active Support extensions (1.day.ago, "hello".pluralize)
- Use instrumentation for performance monitoring
**API Development** ([references/api_development.md](references/api_development.md))
Read this when working with:
- Building JSON APIs with Rails
- API-only applications
- Serialization patterns
- Authentication for APIs (tokens, JWT)
- API versioning strategies
- CORS configuration
Common patterns:
- Use Rails API mode for API-only apps
- Implement proper authentication (OAuth, JWT, API keys)
- Version your APIs from the start
- Use proper HTTP status codes and error responses
</reference_guides>
<workflow>
<starting_new_feature>
**Plan the data model**
- Identify models and their relationships
- Sketch out the database schema
- Consider validations and constraints
**Generate migrations and models**
```bash
rails generate model Article title:string body:text published_at:datetime
rails generate migration AddUserRefToArticles user:referencesSet up associations and validations
- Define relationships in models
- Add validations for data integrity
- Write model tests
Create controllers and routes
bash
rails generate controller Articles index show new create edit update destroy- Or use for full CRUD
rails generate scaffold
Build views
- Create templates using ERB or other templating engines
- Use partials for reusable components
- Leverage form helpers
Write tests
- Model tests for validations and associations
- Controller tests for actions
- System tests for user flows
Iterate and refactor
- Extract common logic to concerns or service objects
- Optimize database queries
- Improve user experience </starting_new_feature> </workflow>
<best_practices>
<code_organization>
- Keep controllers thin (delegate to models/services)
- Use concerns for shared behavior
- Extract complex queries to scopes or query objects
- Use service objects for complex business logic </code_organization>
<common_patterns>
<model_example>
ruby
class Article < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many_attached :images
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
scope :published, -> { where.not(published_at: nil) }
scope :recent, -> { order(created_at: :desc).limit(10) }
def published?
published_at.present? && published_at <= Time.current
end
end</model_example>
<controller_example>
ruby
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@articles = Article.published.includes(:user)
end
def show
end
def create
@article = current_user.articles.build(article_params)
if @article.save
redirect_to @article, notice: 'Article was successfully created.'
else
render :new, status: :unprocessable_entity
end
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :body, :published_at, images: [])
end
end</controller_example>
<routes_example>
ruby
undefinedrails generate model NAME # Generate model
rails generate controller NAME # Generate controller
rails generate scaffold NAME # Generate full CRUD
</common_commands>
<typical_workflow>
1. 生成模型:`rails generate model Article title:string body:text`
2. 运行迁移:`rails db:migrate`
3. 为模型添加关联和验证
4. 生成控制器:`rails generate controller Articles`
5. 在`config/routes.rb`中定义路由
6. 使用ERB模板构建视图
7. 编写测试并迭代
</typical_workflow>
</quick_start>
<reference_guides>
本技能包含按主题分类的详细参考文档。**在处理特定Rails组件时,请务必查阅相关参考文件**:
**Active Record** ([references/active_record.md](references/active_record.md))
在处理以下内容时阅读本部分:
- 模型与数据库操作(CRUD、查询、作用域)
- 数据库迁移与架构变更
- 模型关联(has_many、belongs_to、has_one、has_and_belongs_to_many)
- 验证与自定义验证器
- 回调与生命周期钩子
- PostgreSQL专属特性
- 多数据库配置
- 复合主键
- 加密
常见模式:
- 定义关联时:始终指定inverse_of以提升性能
- 编写迁移:尽可能使用可逆变更
- 查询优化:使用includes/joins避免N+1查询
- 验证:在模型层进行验证,而非仅在控制器中
**Controllers & Views** ([references/controllers_views.md](references/controllers_views.md))
在处理以下内容时阅读本部分:
- Action Controller基础与高级主题
- 视图、局部模板和布局的渲染
- 强参数与参数处理
- Action View助手方法与表单构建器
- 请求/响应周期
- 过滤器(before_action、after_action、around_action)
- 流式传输与文件下载
常见模式:
- 使用强参数白名单允许的属性
- 保持控制器轻量化——业务逻辑应放在模型中
- 使用局部模板实现可复用的视图组件
- 利用视图助手方法处理常见格式化任务
**Routing** ([references/routing.md](references/routing.md))
在处理以下内容时阅读本部分:
- 定义路由(resources、match、get、post等)
- RESTful路由约定
- 嵌套路由与命名空间
- 路由约束与自定义匹配器
- 路由助手方法与URL生成
- 路由关注点实现DRY路由
常见模式:
- 对RESTful路由使用`resources`
- 仅在真正存在层级关系时使用嵌套路由(限制为1层深度)
- 使用浅嵌套实现更简洁的URL
- 利用路由关注点处理共享路由模式
**Testing & Debugging** ([references/testing_debugging.md](references/testing_debugging.md))
在处理以下内容时阅读本部分:
- 编写单元测试(模型、助手方法)
- 控制器测试与集成测试
- 带浏览器自动化的系统测试
- 测试夹具、工厂与测试数据
- 邮件、任务和Cable的测试
- 调试技巧(byebug、rails console)
- Rails日志与调试助手方法
常见模式:
- 先写测试(TDD)或写完代码立即写测试(测试驱动设计)
- 简单场景使用夹具,复杂场景使用工厂
- 测试边缘情况和错误条件
- 对关键用户流程使用系统测试
**Jobs, Mailers & Cable** ([references/jobs_mailers_cable.md](references/jobs_mailers_cable.md))
在处理以下内容时阅读本部分:
- 用于后台处理的Active Job
- 用于发送邮件的Action Mailer
- 用于接收邮件的Action Mailbox
- 用于WebSocket连接的Action Cable
- 队列适配器(Sidekiq、Resque等)
- 邮件发送与测试
常见模式:
- 始终使用Active Job处理异步任务(不要阻塞请求)
- 使用ActionMailer::TestCase测试邮件
- 对实时功能(聊天、通知)使用Action Cable
- 为生产环境配置合适的队列后端
**Assets & Frontend** ([references/assets_frontend.md](references/assets_frontend.md))
在处理以下内容时阅读本部分:
- 资产管道与Sprockets
- JavaScript打包(import maps、esbuild、webpack)
- CSS与预处理器(Sass、Tailwind)
- 用于富文本编辑的Action Text
- 前端框架集成
常见模式:
- 使用资产助手方法(image_tag、javascript_include_tag等)
- 为生产环境配置正确的资产编译
- 利用Rails UJS/Turbo实现动态交互
- 对WYSIWYG内容使用Action Text
**Storage & Caching** ([references/storage_caching.md](references/storage_caching.md))
在处理以下内容时阅读本部分:
- 用于文件上传的Active Storage
- 为模型附加文件
- 图片变体与转换
- 缓存策略(页面、动作、片段、底层)
- 缓存存储(Redis、Memcached)
- 俄罗斯套娃缓存模式
常见模式:
- 所有文件上传都使用Active Storage
- 按需生成图片变体
- 缓存昂贵的计算和查询
- 对动态页面使用片段缓存
**Configuration & Internals** ([references/configuration_internals.md](references/configuration_internals.md))
在处理以下内容时阅读本部分:
- Rails配置选项
- 环境特定设置
- 初始化流程
- 自动加载与预加载
- 线程与并发
- Rack集成
- Rails引擎
- 命令行工具与生成器
- 自定义生成器
常见模式:
- 使用共享设置保持环境配置的DRY
- 使用Rails.application.config进行应用级设置
- 理解开发环境的自动加载与生产环境的预加载差异
- 为重复模式创建自定义生成器
**Security & Performance** ([references/security_performance.md](references/security_performance.md))
在处理以下内容时阅读本部分:
- 安全最佳实践
- XSS、CSRF、SQL注入防护
- 身份验证与授权模式
- 性能调优与优化
- 数据库查询优化
- 资产优化
- 错误报告与监控
常见模式:
- 始终使用强参数(绝不信任用户输入)
- 启用CSRF保护(默认开启)
- 使用预编译语句防止SQL注入
- 为频繁查询的列添加数据库索引
- 优化前先进行性能分析(使用rack-mini-profiler等工具)
**I18n & Support** ([references/i18n_support.md](references/i18n_support.md))
在处理以下内容时阅读本部分:
- 国际化(I18n)设置
- 区域文件与翻译
- Active Support核心扩展
- 时区与日期格式化
- Active Support instrumentation
- 自定义扩展与猴子补丁
常见模式:
- 所有面向用户的字符串都使用I18n.t
- 按控制器/视图层级组织翻译
- 利用Active Support扩展(1.day.ago、"hello".pluralize)
- 使用instrumentation进行性能监控
**API Development** ([references/api_development.md](references/api_development.md))
在处理以下内容时阅读本部分:
- 使用Rails构建JSON API
- 仅API应用
- 序列化模式
- API身份验证(令牌、JWT)
- API版本化策略
- CORS配置
常见模式:
- 对仅API应用使用Rails API模式
- 实现合适的身份验证(OAuth、JWT、API密钥)
- 从一开始就对API进行版本化
- 使用正确的HTTP状态码和错误响应
</reference_guides>
<workflow>
<starting_new_feature>
**规划数据模型**
- 识别模型及其关系
- 草拟数据库架构
- 考虑验证与约束
**生成迁移和模型**
```bash
rails generate model Article title:string body:text published_at:datetime
rails generate migration AddUserRefToArticles user:references设置关联和验证
- 在模型中定义关系
- 添加验证以保证数据完整性
- 编写模型测试
创建控制器和路由
bash
rails generate controller Articles index show new create edit update destroy- 或使用生成完整CRUD功能
rails generate scaffold
构建视图
- 使用ERB或其他模板引擎创建模板
- 使用局部模板实现可复用组件
- 利用表单助手方法
编写测试
- 针对验证和关联的模型测试
- 针对动作的控制器测试
- 针对用户流程的系统测试
迭代与重构
- 将通用逻辑提取到关注点或服务对象
- 优化数据库查询
- 提升用户体验 </starting_new_feature> </workflow>
<best_practices>
<code_organization>
- 保持控制器轻量化(将逻辑委托给模型/服务)
- 使用关注点处理共享行为
- 将复杂查询提取到作用域或查询对象
- 使用服务对象处理复杂业务逻辑 </code_organization>
<common_patterns>
<model_example>
ruby
class Article < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many_attached :images
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true
scope :published, -> { where.not(published_at: nil) }
scope :recent, -> { order(created_at: :desc).limit(10) }
def published?
published_at.present? && published_at <= Time.current
end
end</model_example>
<controller_example>
ruby
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@articles = Article.published.includes(:user)
end
def show
end
def create
@article = current_user.articles.build(article_params)
if @article.save
redirect_to @article, notice: 'Article was successfully created.'
else
render :new, status: :unprocessable_entity
end
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :body, :published_at, images: [])
end
end</controller_example>
<routes_example>
ruby
undefinedconfig/routes.rb
config/routes.rb
Rails.application.routes.draw do
root 'articles#index'
resources :articles do
resources :comments, only: [:create, :destroy]
end
namespace :admin do
resources :articles
end
end
</routes_example>
</common_patterns>
<version_notes>
This skill is based on Rails 8.1.1. Key recent features:
- Solid Queue, Solid Cache, and Solid Cable for built-in infrastructure
- Enhanced Turbo integration
- Improved authentication generators
- Better type checking with RBS support
- Progressive Web App features
When working with older Rails versions, check the upgrade guides in the references for migration paths and deprecated features.
</version_notes>
<troubleshooting>
When stuck on a Rails problem:
1. Check the relevant reference file first
2. Use `rails console` to experiment with code
3. Review the Rails guides at guides.rubyonrails.org
4. Check the API documentation at api.rubyonrails.org
5. Search GitHub issues for known problems
Remember: Rails is designed to make common tasks easy and follow sensible conventions. If something feels too difficult, there's likely a Rails way to do it more simply.
</troubleshooting>
<success_criteria>
You're using this skill effectively when:
- You consult the appropriate reference file before implementing Rails features
- You follow Rails conventions (RESTful routes, naming patterns, file organization)
- You leverage Rails generators and built-in functionality
- Your code follows the best practices outlined above
- Tests are written alongside feature development
- Security and performance considerations are addressed proactively
</success_criteria>Rails.application.routes.draw do
root 'articles#index'
resources :articles do
resources :comments, only: [:create, :destroy]
end
namespace :admin do
resources :articles
end
end
</routes_example>
</common_patterns>
<version_notes>
本技能基于Rails 8.1.1版本。近期关键特性:
- 内置的Solid Queue、Solid Cache和Solid Cable基础设施
- 增强的Turbo集成
- 改进的身份验证生成器
- 更好的RBS类型检查支持
- 渐进式Web应用特性
在使用旧版Rails时,请查阅参考资料中的升级指南,了解迁移路径和已弃用特性。
</version_notes>
<troubleshooting>
遇到Rails问题时:
1. 首先查阅相关参考文件
2. 使用`rails console`调试代码
3. 查看Rails官方指南guides.rubyonrails.org
4. 查看API文档api.rubyonrails.org
5. 搜索GitHub问题寻找已知问题
记住:Rails的设计初衷是让常见任务变得简单,并遵循合理的约定。如果某件事做起来太复杂,很可能有更简单的Rails方式来实现。
</troubleshooting>
<success_criteria>
有效使用本技能的标准:
- 在实现Rails特性前查阅对应的参考文件
- 遵循Rails约定(RESTful路由、命名模式、文件组织)
- 利用Rails生成器和内置功能
- 代码符合上述最佳实践
- 与特性开发同步编写测试
- 主动考虑安全和性能问题
</success_criteria>