Cursor rule
.cursor/rules/rails-rules.mdcRails Development Rules - The Rails Way with AI Agents
Cursor rules
Quality
84/100
Scores the file, not the repository.Length
2,015 words
66 headings · 3 code blocksRepository
54
— · pushed 410 days agoLast changed
3 days ago
First indexed 3 days ago.123456# Rails Development Rules - The Rails Way with AI Agents7***Built for: Solo developer + AI agents, Linear MCP integration, maximum joy***89## Core Philosophy10You are building a Rails 8+ application following The Rails Way™. Code should be:11- Convention over configuration12- Database-first design13- Progressive enhancement with Hotwire14- Zero-build frontend approach15- Test-driven with Minitest16- Optimized for AI agent collaboration17- Lean, readable, and maintainable1819## Rails 8+ Stack Preferences20- **Authentication**: Rails built-in (`rails generate authentication`)21- **Background Jobs**: Solid Queue (default Rails 8)22- **Caching**: Solid Cache (database-backed, Redis when needed)23- **WebSockets**: Action Cable with Solid Cable adapter24- **Database**: PostgreSQL with Active Record25- **Frontend**: Hotwire (Turbo + Stimulus) + TailwindCSS26- **Asset Pipeline**: Propshaft (simpler, no-build approach)27- **Testing**: Minitest with fixtures (no RSpec, no factories)28- **Rich Text**: Action Text for content editing29- **File Uploads**: Active Storage with direct uploads30- **Deployment**: Kamal with Docker31- **Code Quality**: StandardRB for linting/formatting32- **Development Tools**: Bullet gem for N+1 detection, Annotate gem for schema docs33- **Error Tracking**: Rails built-in error reporter3435## Detailed Guides36This document provides core principles. For detailed implementation guidance, see:3738- **[core.md](rails/core.md)** - Rails 8 conventions and patterns39- **[models.md](rails/models.md)** - Active Record patterns and best practices40- **[controllers.md](rails/controllers.md)** - Controller design and RESTful patterns41- **[services.md](rails/services.md)** - Service objects and business logic42- **[testing.md](rails/testing.md)** - Testing philosophy and Minitest patterns43- **[security.md](rails/security.md)** - Security best practices and authorization44- **[performance.md](rails/performance.md)** - Database optimization and caching45- **[api.md](rails/api.md)** - API design and versioning (when needed)46- **[importmaps.md](rails/importmaps.md)** - JavaScript without build steps47- **[hotwire.md](rails/hotwire.md)** - Turbo & Stimulus patterns48- **[views.md](rails/views.md)** - View helpers and rendering49- **[styling.md](rails/styling.md)** - TailwindCSS integration50- **[background-jobs.md](rails/background-jobs.md)** - Solid Queue configuration51- **[deployment.md](rails/deployment.md)** - Kamal deployment guide52- **[mobile.md](rails/mobile.md)** - Hotwire Native for mobile apps (optional)5354## File Organization & Naming5556### Consistent Directory Structure57```58app/59├── controllers/60│ ├── concerns/61│ └── application_controller.rb62├── models/63│ ├── concerns/64│ └── application_record.rb65├── views/66│ ├── layouts/67│ ├── shared/68│ └── [resource_name]/69├── services/70├── jobs/71├── channels/72├── mailers/73└── helpers/74```7576### Naming Conventions for AI Agents77- **Classes**: PascalCase, descriptive (`UserRegistrationService`, `InvoicePaymentProcessor`)78- **Files**: snake_case matching class name (`user_registration_service.rb`)79- **Methods**: snake_case, verb-first for actions (`process_payment`, `calculate_total`)80- **Variables**: snake_case, noun-first (`current_user`, `payment_amount`)81- **Constants**: SCREAMING_SNAKE_CASE (`MAX_RETRY_ATTEMPTS`, `DEFAULT_CURRENCY`)8283### AI Agent File Patterns84Always organize files predictably:85```86app/models/user.rb # Model: singular87app/controllers/users_controller.rb # Controller: plural + _controller88app/services/user_registration.rb # Service: domain + action89app/jobs/send_welcome_email_job.rb # Job: action + _job90app/views/users/index.html.erb # View: controller/action91```9293### AI-Friendly Documentation94- Include purpose statement for AI comprehension95- Reference Linear ticket context (ID-123)96- Document key dependencies and return values97- Specify potential errors and exceptions98- Keep documentation close to code99100## Linear Integration (Project Management)101102### Overview103This section contains Linear-specific integration patterns. The same principles can be adapted for other project management tools by replacing Linear ticket formats and magic words with platform-specific equivalents.104105### Commit Message Format106- Use Conventional Commits format with issue references107- Structure: `type(scope): description` followed by body and footer108- Include ticket reference in commit body or footer109- Example:110```111 feat: add magic link authentication112113 Implements passwordless login flow114 Fixes ID-123115```116117### Issue Linking118- Use semantic keywords to manage issue state through commits119- **Closing keywords**: `close`, `closes`, `closed`, `closing fix`, `fixes`, `fixed`, `fixing`, `resolve`, `resolves`, `resolved`, `resolving`, `complete`, `completes`, `completed`, `completing` (auto-close issues)120- **Reference keywords**: `ref`, `refs`, `references`, `part of`, `related to`, `contributes to`, `toward`, `towards` (link without closing)121- Support multiple issues: `Fixes ID-123, ID-456`122123### Branch Strategy124- Follow GitHub Flow with descriptive branch names125- Format: `type/ticket-id/brief-description`126- Example: `feat/id-123/magic-link-login`127- Keep branches short-lived and focused128129### Documentation Integration130- Reference tickets in code comments for complex logic131- Include ticket IDs in migration descriptions132- Link issues in test descriptions for context133- Document architectural decisions with ticket references134135## Models & Active Record136137### Model Design Principles138- Keep models focused on data integrity and business rules139- Use schema annotations (annotate gem) for documentation140- Order model contents consistently: constants, includes, associations, validations, callbacks, scopes, methods141- Implement database constraints to match validations142- Use concerns for shared behavior across models143144### Model Best Practices145- Always index foreign keys and frequently queried columns146- Use counter caches for association counts147- Implement scopes for common query patterns148- Keep callbacks minimal - prefer service objects for complex logic149- Use `dependent:` options to maintain referential integrity150151### Database Design152- Design normalized schemas by default153- Use appropriate PostgreSQL data types154- Implement database-level constraints155- Create partial indexes for performance156- Document complex queries and decisions157158See **[models.md](rails/models.md)** for detailed Active Record patterns.159160## Controllers161162### Controller Principles163- Keep controllers thin and focused on HTTP concerns164- Use before_action filters for common setup165- Follow RESTful conventions strictly166- Handle multiple response formats (HTML, Turbo Stream, JSON)167- Implement proper error handling with appropriate status codes168169### Controller Patterns170- Always use strong parameters for user input171- Prefer redirect after mutations over render172- Keep business logic in models or service objects173- Use concerns for shared controller behavior174- Implement resourceful routes whenever possible175176See **[controllers.md](rails/controllers.md)** for detailed controller patterns.177178## Service Objects179180### When to Use Service Objects181- Complex business logic spanning multiple models182- External API integrations183- Multi-step processes with transactions184- Operations that don't naturally fit in a model185- Background job logic that needs testing186187### Service Object Principles188- Keep services focused on a single operation189- Use clear, descriptive names190- Return meaningful results (success/failure)191- Make services easy to test in isolation192- Include proper error handling193194See **[services.md](rails/services.md)** for service object patterns.195196## Testing Philosophy197198### The Rails Way of Testing199- Use fixtures over factories for simplicity and speed200- Write system tests for critical user flows201- Unit test models and services thoroughly202- Test controllers only for complex authorization203- Always test happy path and edge cases204205### Testing Best Practices206- Keep tests fast and focused207- Use descriptive test names208- Test behavior, not implementation209- Mock external services appropriately210- Maintain high coverage without obsessing211212See **[testing.md](rails/testing.md)** for comprehensive testing patterns.213214## Background Jobs215216### Job Design Principles217- Make all jobs idempotent and retryable218- Keep jobs small and focused219- Pass simple arguments (IDs, not objects)220- Design for eventual consistency221- Handle failures gracefully222223### Solid Queue Configuration224- Use database-backed queuing for simplicity225- Configure workers based on priorities226- Set appropriate concurrency limits227- Monitor queue depth and latency228- Implement proper error handling229230See **[background-jobs.md](rails/background-jobs.md)** for Solid Queue patterns.231232## Mailers233234### Mailer Best Practices235- Keep mailers simple and focused236- Use layouts for consistent email design237- Test email delivery in development238- Implement proper error handling239- Consider delivery performance240241### Email Design242- Design for email client limitations243- Provide text alternatives244- Test across email clients245- Keep templates maintainable246- Handle bounces appropriately247248## Performance & Optimization249250### Query Optimization251- Avoid N+1 queries with proper includes252- Use database-level operations when possible253- Implement appropriate indexes254- Profile before optimizing255- Monitor performance in production256257### Caching Strategy258- Use Russian doll caching for nested content259- Implement fragment caching for expensive views260- Cache at the appropriate level261- Use cache keys that auto-expire262- Monitor cache effectiveness263264See **[performance.md](rails/performance.md)** for detailed optimization patterns.265266## Security Best Practices267268### Core Security Principles269- Always use strong parameters270- Implement proper authentication and authorization271- Sanitize user input appropriately272- Use CSRF protection for all forms273- Keep credentials in Rails credentials system274275### Security Patterns276- Validate input at multiple levels277- Implement rate limiting for APIs278- Use secure headers in production279- Audit dependencies regularly280- Follow OWASP guidelines281282See **[security.md](rails/security.md)** for comprehensive security patterns.283284## Error Handling285286### Error Handling Strategy287- Use Rails error reporter for centralized tracking288- Implement custom error pages289- Handle exceptions at appropriate levels290- Provide meaningful error messages291- Log errors with sufficient context292293### Logging Best Practices294- Use appropriate log levels295- Include structured data in logs296- Avoid logging sensitive information297- Implement request correlation IDs298- Monitor logs for patterns299300## Code Style & Conventions301302### Method Organization303- Order methods logically: public, protected, private304- Group related methods together305- Use descriptive method names306- Keep methods small and focused307- Document complex logic308309### Rails Conventions310- Use `?` suffix for boolean methods311- Use `!` suffix for dangerous methods312- Follow Rails naming patterns strictly313- Prefer Rails helpers over custom solutions314- Keep code idiomatic to Rails315316### Code Quality Tools317- Use StandardRB for consistent formatting318- Run Bullet gem to detect N+1 queries319- Keep schema annotations current320- Use pre-commit hooks for quality321- Review code for Rails best practices322323## Secrets & Configuration324325### Credential Management326- Use Rails credentials for all secrets327- Never commit sensitive data328- Use environment variables for non-sensitive config329- Document credential requirements330- Rotate credentials regularly331332### Configuration Best Practices333- Keep configuration DRY334- Use Rails configuration patterns335- Document environment-specific settings336- Validate configuration on boot337- Handle missing configuration gracefully338339## AI Agent Collaboration340341### Documentation for AI Agents342- Write clear, comprehensive comments343- Use consistent patterns throughout344- Document business logic thoroughly345- Explain non-obvious decisions346- Include examples where helpful347348### Predictable Patterns349- Follow Rails conventions religiously350- Use standard file organization351- Keep naming consistent352- Write explicit rather than clever code353- Maintain comprehensive test coverage354355### Task Breakdown356- Reference Linear tickets clearly357- Break complex tasks into phases358- Document dependencies between tasks359- Keep scope manageable360- Communicate progress clearly361362## Development Workflow363364### Project Management Integration365- The workflow supports various project management tools366- Linear integration is current default (see Linear Integration section)367- Adapt ticket references and workflows to your chosen platform368- Maintain consistent commit and branch naming patterns369370### Local Development371- Use Rails generators appropriately372- Keep development close to production373- Use Rails console for debugging374- Implement helpful seed data375- Document setup requirements376377### Git Workflow378- Follow GitHub Flow for simplicity and clarity379- Create feature branches from main/master380- Keep commits atomic and well-documented381- Open pull requests early for visibility382- Merge after review and CI checks pass383384### Continuous Integration385- Run tests automatically on every push386- Deploy to staging via Kamal after main branch updates387- Use branch protection rules for quality gates388- Automate security and dependency checks389- Keep CI fast and focused on essentials390391### Code Review392- Check for Rails best practices393- Verify test coverage394- Review security implications395- Ensure performance considerations396- Validate documentation completeness397398## Production Considerations399400### Deployment Checklist401- Run tests before deployment402- Check migration safety403- Verify environment configuration404- Monitor deployment progress405- Have rollback plan ready406407### Production Best Practices408- Use health check endpoints409- Implement proper monitoring410- Configure appropriate timeouts411- Set up error alerting412- Plan for scaling413414See **[deployment.md](rails/deployment.md)** for Kamal deployment details.415416## Final Reminders417418### Always Prefer Rails Conventions419- Trust the framework's decisions420- Use built-in solutions first421- Follow established patterns422- Avoid premature optimization423- Keep solutions simple424425### Code Quality Checklist426- [ ] Tests written and passing427- [ ] No N+1 queries detected428- [ ] Code follows Rails conventions429- [ ] Security considerations addressed430- [ ] Performance implications considered431- [ ] Documentation is complete432- [ ] Linear ticket referenced433- [ ] AI agents can understand the code434435Remember: Rails provides everything you need. Trust the framework, follow conventions, and focus on delivering value. Write code that's a joy to work with.436437Happy coding! 🚂 🚀438
Also in levifig/rails-instructions
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| levifig/rails-instructions.github/instructions/rails-core.instructions.md · 54 | Copilot instructions | teststylearchtesting-strategy+5 | 68/100 | 3 days ago | |
| levifig/rails-instructions.cursor/rules/guidelines.mdc · 54 | Cursor rules | teststyletesting-strategysecurity+4 | 71/100 | 3 days ago | |
| levifig/rails-instructions.github/copilot-instructions.md · 54 | Copilot instructions | teststyletesting-strategysecurity+4 | 71/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-api.instructions.md · 54 | Copilot instructions | testlint-formatstyletesting-strategy+7 | 67/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-background-jobs.instructions.md · 54 | Copilot instructions | teststyletesting-strategydatabase+2 | 63/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-controllers.instructions.md · 54 | Copilot instructions | teststylesecurityapi+1 | 56/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-deployment.instructions.md · 54 | Copilot instructions | setupstylesecuritydatabase+2 | 52/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-hotwire.instructions.md · 54 | Copilot instructions | teststylesecurityperformance+1 | 56/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-importmaps.instructions.md · 54 | Copilot instructions | teststylesecuritydatabase+2 | 56/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-mobile.instructions.md · 54 | Copilot instructions | styleuiperformance | 66/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-models.instructions.md · 54 | Copilot instructions | teststylearchtypes+4 | 60/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-performance.instructions.md · 54 | Copilot instructions | teststylegitdatabase+2 | 56/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-security.instructions.md · 54 | Copilot instructions | teststylesecuritydependencies+3 | 63/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-services.instructions.md · 54 | Copilot instructions | teststylearchtesting-strategy+4 | 75/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-styling.instructions.md · 54 | Copilot instructions | styledatabaseuiperformance+3 | 59/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-testing.instructions.md · 54 | Copilot instructions | teststyletesting-strategysecurity+2 | 56/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails-views.instructions.md · 54 | Copilot instructions | teststylearchsecurity+3 | 60/100 | 3 days ago | |
| levifig/rails-instructions.github/instructions/rails.instructions.md · 54 | Copilot instructions | testlint-formatstylearch+9 | 84/100 | 3 days ago |
Diff against .github/instructions/rails-core.instructions.md Diff against .cursor/rules/guidelines.mdc Diff against .github/copilot-instructions.md Diff against .github/instructions/rails-api.instructions.md Diff against .github/instructions/rails-background-jobs.instructions.md Diff against .github/instructions/rails-controllers.instructions.md Diff against .github/instructions/rails-deployment.instructions.md Diff against .github/instructions/rails-hotwire.instructions.md Diff against .github/instructions/rails-importmaps.instructions.md Diff against .github/instructions/rails-mobile.instructions.md Diff against .github/instructions/rails-models.instructions.md Diff against .github/instructions/rails-performance.instructions.md Diff against .github/instructions/rails-security.instructions.md Diff against .github/instructions/rails-services.instructions.md Diff against .github/instructions/rails-styling.instructions.md Diff against .github/instructions/rails-testing.instructions.md Diff against .github/instructions/rails-views.instructions.md Diff against .github/instructions/rails.instructions.md
