---
description: Rails Models and Active Record Guide
applyTo: "app/models/**/*.rb"
---

# Rails Models and Active Record Guide

## Core Philosophy

- Models are the heart of your Rails application
- Keep business logic and data integrity in models
- Use database constraints to enforce rules
- Design for clarity and maintainability
- Trust Active Record's conventions

## Model Design Principles

- Focus models on their core domain responsibility
- Keep models cohesive and loosely coupled
- Use descriptive names that reflect business concepts
- Avoid God objects - split large models when needed
- Document complex business rules clearly

## Schema Management

- Always use the annotate gem for schema documentation
- Keep schema annotations at the top of model files
- Run annotate after every migration
- Review schema changes carefully before committing
- Document non-obvious column purposes

## Model Organization

- Order model contents consistently for readability
- Place constants at the top
- Group related elements together
- Keep public interface minimal
- Document complex logic thoroughly

## Associations Best Practices

- Define all relationships explicitly
- Use appropriate dependent options
- Consider bi-directional associations carefully
- Avoid circular dependencies
- Document association purposes when not obvious

## Validation Strategy

- Validate at the model level always
- Use database constraints to match validations
- Keep validation messages user-friendly
- Group related validations together
- Test all validation scenarios

## Database Constraints

- Add NOT NULL constraints for required fields
- Use unique indexes for uniqueness validations
- Implement foreign key constraints
- Add check constraints for complex rules
- Document constraint purposes in migrations

## Scopes and Queries

- Create scopes for commonly used queries
- Keep scope names descriptive and intention-revealing
- Chain scopes for complex queries
- Avoid scopes with side effects
- Use class methods for scopes with parameters

## Callbacks Guidelines

- Use callbacks sparingly and purposefully
- Keep callback methods private
- Avoid callbacks that touch other models
- Document callback purposes clearly
- Consider service objects for complex workflows

## Performance Considerations

- Always index foreign keys
- Add indexes for frequently queried columns
- Use counter caches for association counts
- Implement includes to avoid N+1 queries
- Profile queries before optimizing

## Concerns and Modules

- Extract shared behavior into concerns
- Keep concerns focused on single responsibilities
- Name concerns based on the behavior they provide
- Document concern dependencies
- Test concerns thoroughly

## Enums and Constants

- Use enums for status fields with fixed values
- Define constants for magic numbers
- Keep enum values meaningful
- Document enum state transitions
- Consider state machines for complex workflows

## Data Integrity

- Implement validations that match business rules
- Use transactions for multi-step operations
- Handle race conditions appropriately
- Validate data consistency regularly
- Plan for data migration scenarios

## Testing Models

- Test all validations thoroughly
- Verify association behavior
- Test scopes with various data sets
- Check callback effects
- Ensure data integrity in edge cases

## Migration Best Practices

- Keep migrations focused and reversible
- Add indexes in the same migration as columns
- Use strong data types
- Document migration purposes
- Test migrations up and down

## Active Record Patterns

- Use find_or_create_by for idempotent operations
- Implement soft deletes when audit trails needed
- Use optimistic locking for concurrent updates
- Leverage Active Record's built-in features
- Avoid raw SQL unless necessary

## Model Security

- Never trust user input directly
- Use parameterized queries always
- Implement attribute protection appropriately
- Audit sensitive data access
- Encrypt sensitive attributes

## Documentation Standards

- Document complex business logic
- Explain non-obvious validations
- Describe association purposes
- Note performance considerations
- Include usage examples for complex methods

## Common Anti-Patterns

- Avoid callbacks that send emails or call APIs
- Don't put view logic in models
- Prevent models from knowing about controllers
- Skip validations only when absolutely necessary
- Don't bypass Active Record without good reason

## Refactoring Guidelines

- Extract complex queries to scopes
- Move multi-model logic to service objects
- Split large models along domain boundaries
- Keep methods small and focused
- Maintain backward compatibility

## Best Practices Summary

- Trust Active Record conventions
- Keep models focused on data and business rules
- Use database constraints for data integrity
- Write comprehensive tests
- Document complex logic clearly

Remember: Models are the foundation of your Rails application. Keep them clean, well-tested, and focused on their core responsibilities.
