---
description: Rails 8 Core Principles Guide
applyTo: "**/*.rb"
---

# Rails 8 Core Principles Guide

## Core Philosophy

- Follow Rails conventions religiously - they exist for good reasons
- Embrace the monolith - most applications don't need microservices
- Use Rails 8's built-in features before reaching for external gems
- Write code that's a joy to work with, not just functional
- Optimize for developer happiness and productivity

## Rails 8 Stack Defaults

- Use SQLite for development and production by default
- Leverage Solid Queue for background job processing
- Implement Solid Cache for caching with database backend
- Use Solid Cable for WebSocket connections
- Embrace Propshaft for asset pipeline simplicity

## Framework Principles

- Convention over configuration in all decisions
- Database-driven design with Active Record at the center
- RESTful resources and routes by default
- Server-side rendering with Hotwire enhancements
- Progressive enhancement over client-side complexity

## Model Design Principles

- Keep models focused on data integrity and business rules
- Use Active Record validations extensively
- Implement scopes for common query patterns
- Add database indexes for foreign keys and frequently queried columns
- Use concerns for shared behavior across models

## Model Best Practices

- Include schema annotations in all model files
- Order model contents consistently: constants, includes, associations, validations, callbacks, scopes, methods
- Keep callbacks minimal - consider service objects for complex logic
- Use `dependent:` options on associations to maintain referential integrity
- Implement proper counter caches for performance

## Controller Principles

- Keep controllers thin and focused on HTTP concerns
- Use before_action filters for common setup and authorization
- Respond to multiple formats (HTML, Turbo Stream, JSON) appropriately
- Follow REST conventions for action names
- Handle errors gracefully with proper HTTP status codes

## Controller Patterns

- Use strong parameters for all user input
- Prefer redirect_to with notice/alert over render after mutations
- Implement resourceful routes whenever possible
- Keep business logic out of controllers
- Use concerns for shared controller behavior

## Service Object Guidelines

- Create service objects for complex multi-model operations
- Use when business logic doesn't naturally fit in a model
- Keep service objects focused on a single operation
- Return meaningful results (success/failure with errors)
- Make service objects easy to test in isolation

## View Architecture

- Use partials for reusable view components
- Keep logic out of views - use helpers or decorators
- Follow Rails naming conventions for templates
- Use Rails form helpers for all forms
- Implement proper semantic HTML structure

## Testing Philosophy

- Write tests first (TDD) for all new features
- Use Rails' built-in Minitest framework
- Prefer fixtures over factories for test data
- Write system tests for critical user paths
- Keep tests fast and focused

## Testing Patterns

- Test models thoroughly including validations and scopes
- Test controllers for authorization and response formats
- Use system tests for JavaScript interactions
- Mock external services in tests
- Maintain high test coverage without obsessing over 100%

## Background Jobs

- Use Active Job interface for all background processing
- Design jobs to be idempotent and retryable
- Keep jobs small and focused on single tasks
- Use appropriate queue priorities
- Handle errors with proper retry strategies

## Database Design

- Use database constraints to enforce data integrity
- Create appropriate indexes for query performance
- Use foreign key constraints in migrations
- Design normalized schemas by default
- Document complex queries and database decisions

## Caching Strategy

- Use Russian doll caching for nested content
- Cache expensive queries at the model level
- Implement fragment caching for complex views
- Use cache keys that automatically expire
- Monitor cache hit rates in production

## Security Practices

- Always use strong parameters in controllers
- Implement proper authentication and authorization
- Use CSRF protection for all forms
- Sanitize user input when displaying HTML
- Keep credentials in Rails credentials system

## Performance Guidelines

- Avoid N+1 queries with proper includes
- Use database-level operations when possible
- Implement pagination for large datasets
- Profile before optimizing
- Monitor performance in production

## API Design (When Needed)

- Version APIs using URL path versioning (/api/v1)
- Use consistent JSON response formats
- Implement proper HTTP status codes
- Document API endpoints thoroughly
- Use token-based authentication for APIs

## Active Storage Configuration

- Configure direct uploads for better performance
- Implement virus scanning for user uploads
- Use variants for image transformations
- Set appropriate service limits
- Clean up orphaned attachments regularly

## Action Text Implementation

- Use for rich text content editing
- Configure image upload limits
- Implement proper sanitization
- Style with consistent CSS
- Handle attachments appropriately

## Action Cable Usage

- Use Solid Cable adapter for simpler deployment
- Design channels for specific features
- Implement proper authorization in channels
- Keep broadcast payloads minimal
- Handle connection failures gracefully

## Development Workflow

- Use Rails generators appropriately
- Keep development environment close to production
- Use Rails console effectively for debugging
- Implement proper seed data
- Document non-obvious decisions

## Code Organization

- Follow Rails directory structure strictly
- Use concerns for shared behavior
- Keep lib/ for non-Rails specific code
- Organize tests mirroring app structure
- Use meaningful file and class names

## Deployment Considerations

- Use Rails' built-in health check endpoint
- Configure proper database connection pools
- Set appropriate timeouts
- Use encrypted credentials for secrets
- Monitor application performance

## Error Handling

- Use Rails error reporter for centralized error tracking
- Implement custom error pages
- Log appropriately at different levels
- Handle exceptions at appropriate levels
- Provide meaningful error messages

## Upgrade Strategy

- Stay current with Rails versions
- Read upgrade guides thoroughly
- Update dependencies regularly
- Test thoroughly after upgrades
- Use deprecation warnings as guides

## Best Practices Summary

- Write code for humans first, computers second
- Follow Rails conventions unless you have excellent reasons not to
- Keep it simple - you probably don't need that complexity
- Test everything that could possibly break
- Make your code a joy for the next developer (probably you)

Remember: Rails 8 provides everything you need to build modern web applications. Trust the framework and focus on your business logic.
